一、基本參數類型
1、基本類型: String,Int,Float,Boolean和ID 五個。可以在schema聲明的時候直接使用;
2、[類型] 代表數組, 例如: [Int] 代表整型數組
二、參數傳遞
1、和js傳遞參數一樣,小括號內定義形參,但是注意:參數需要定義類型;
2、!(嘆號) 代表參數不能為空;
例如:
type Query {
//hello方法中有兩個參數name和age,name類型為String, age類型為Int, 并且age不能為空,返回值為整型數組
hello(name: String, age: Int! ) : [Int]
}
三、自定義參數類型
GraphQL允許用戶自定義參數類型,通常用來描述要獲取的資源的屬性
const express = require('express');
const {buildSchema} = require('graphql');
const {graphqlHTTP} = require('express-graphql');
// 定義Schema, 查詢方法和返回值類型
const schema = buildSchema(`
// Account 為自定義類型
type Account {
name: String
age: Int
sex: String
department: String
salary(city: String): Int
}
type Query {
getClassMates(classNo: Int!): [String]
account(username: String): Account
}
`)
//定義查詢對應的處理器
const root = {
getClassMates({classNo}) {
const obj = {
11: ['張三', '李四', '王五'],
12: ['張飛', '曹操', '關羽']
}
return obj[classNo];
},
account({username}) {
const name = username;
const age = 12;
const sex = '男';
const department = '測試部';
const salary = ({city}) => {
if (city == '北京' || city == '上海' || city == '廣州') {
return 10000;
}
return 4000;
}
return {
name,
age,
sex,
department,
salary
}
}
}
const app = express();
app.use('/graphql', graphqlHTTP({
schema: schema,
rootValue: root,
graphiql: true
}))
app.listen(3000);
image.png