2019GraphQL入门到精通  ​​https://www.bilibili.com/video/BV1Ab411H7Yv?from=search&seid=16813706797539177189​

视频 4

GraphQL基本参数类型

  • String, Int, Float, Boolean和ID。在schema声明时直接使用。 (ID不能重复使用)
  • [类型]代表数组,例如:[Int]代表整型数组

GraphQL基本参数传递

  • 与js传递参数一样,小括号内定义形参,注意:参数需要定义类型。
  • !(叹号)代表参数不能为空。
type Query {
rollDice (numDice: Int!, numSides: Int): [Int]
}

//numDice不能为空,numSides可以为空,返回值为Int类型数组

GraphQL允许客户自定义参数类型,通常用来描述想要获取的资源的属性。

type Account {
name: String
age: Int
sex: String
department: String
}
type Query {
account(name: String):Account
}

baseType.js

const express = require('express');
const graphqlHTTP = require('express-graphql');
const {buildSchema} = require('graphql');

const schema = buildSchema (`
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 = {
31: ['Jim', 'Jack', 'Jhon'],
61: ['Kate', 'Kimi', 'Kevin']
}
return obj[classNo];
},
account({username}) {
const name = username;
const sex = 'm';
const age = 18;
const department = 'IT';
const salary = ({city}) => {
if (city == "北京" || city == "上海") {
return 10000;
}
return 3000;
}
return { // 无序排列
name,
sex,
age,
department,
salary
}
}

}
const app = express();
app.use('/graphql', graphqlHTTP({
schema:schema,
rootValue: root,
graphiql: true //打开调试模式(开发者模式)
}))
app.listen(3000);

运行baseType.js

step1. node baseType.js

step2. 打开浏览器,输入localhost:3000

GraphQL - 参数类型与参数传递_ide

指定城市为北京 

GraphQL - 参数类型与参数传递_参数类型_02

不指定特定城市

GraphQL - 参数类型与参数传递_参数类型_03