一、基本參數(shù)類(lèi)型
1太防、基本類(lèi)型: String妻顶,Int,F(xiàn)loat蜒车,Boolean和ID 五個(gè)讳嘱。可以在schema聲明的時(shí)候直接使用酿愧;
2沥潭、[類(lèi)型] 代表數(shù)組, 例如: [Int] 代表整型數(shù)組
二嬉挡、參數(shù)傳遞
1钝鸽、和js傳遞參數(shù)一樣汇恤,小括號(hào)內(nèi)定義形參,但是注意:參數(shù)需要定義類(lèi)型拔恰;
2因谎、!(嘆號(hào)) 代表參數(shù)不能為空颜懊;
例如:
type Query {
//hello方法中有兩個(gè)參數(shù)name和age,name類(lèi)型為String财岔, age類(lèi)型為Int, 并且age不能為空,返回值為整型數(shù)組
hello(name: String, age: Int! ) : [Int]
}
三河爹、自定義參數(shù)類(lèi)型
GraphQL允許用戶(hù)自定義參數(shù)類(lèi)型匠璧,通常用來(lái)描述要獲取的資源的屬性
const express = require('express');
const {buildSchema} = require('graphql');
const {graphqlHTTP} = require('express-graphql');
// 定義Schema, 查詢(xún)方法和返回值類(lèi)型
const schema = buildSchema(`
// Account 為自定義類(lèi)型
type Account {
name: String
age: Int
sex: String
department: String
salary(city: String): Int
}
type Query {
getClassMates(classNo: Int!): [String]
account(username: String): Account
}
`)
//定義查詢(xún)對(duì)應(yīng)的處理器
const root = {
getClassMates({classNo}) {
const obj = {
11: ['張三', '李四', '王五'],
12: ['張飛', '曹操', '關(guān)羽']
}
return obj[classNo];
},
account({username}) {
const name = username;
const age = 12;
const sex = '男';
const department = '測(cè)試部';
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