「这是我参与2022首次更文挑战的第6天,活动详情查看:2022首次更文挑战」
graphql在线文档
紧接着上节课, 我们已在浏览器上看到graphql的运行效果, 点击右侧的Docs, 可看到我们可以查询的数据类型
点击上图的query: RootQueryType, 我们可进一步看到person(id: String): Person, 即我们定义的Person类型, 可以通过下面代码查询指定id数据
注意: person(id:"2")里面的2必须用双引号括起来
我们亦可以指定, 接口只需返回name, 如下图所示:
GraphQLID
之前在查找人时, person(id:"2")里面的2必须用双引号, 这是因为我们在定义PersonType结构体时, 已定义id的类型为GraphQLString
const PersonType = new GraphQLObjectType({
name: 'Person',
fields: () => ({
id: {type: GraphQLString},
...
})
})
若我们需要查询的时候, 使用person(id:2), 则需要引入GraphQLID, 部分代码如下所示:
const {
GraphQLObjectType,
GraphQLString,
GraphQLSchema,
GraphQLID
} = graphql
const PersonType = new GraphQLObjectType({
name: 'Person',
fields: () => ({
id: {type: GraphQLID},
...
})
})
const RootQuery = new GraphQLObjectType({
name: 'RootQueryType',
fields: {
person: {
type: PersonType,
args: {
id: {type: GraphQLID}
},
}
}
})
再次查询时, 可查询到结果
GraphQLInt
我们给PersonType新增一个age字段, 此时需引入GraphQLInt, 标明该字段为Int类型
const {
...
GraphQLInt
} = graphql
var persons = [
{name: 'zhangsan', sex: 'male', age: 24, id: "1"},
{name: 'lisi', sex: 'male', age: 28, id: "2"},
{name: 'lili', sex: 'female', age: 31,id: "3"}
]
const PersonType = new GraphQLObjectType({
name: 'Person',
fields: () => ({
...,
age: {type:GraphQLInt}
})
})
再次执行查询
JobType
除了上面的PersonType, 我们再增加一个工作类型JobType, 代码如下所示:
var jobs = [
{name: 'front-end engineer', department: 'Programming', id: "1"},
{name: 'back-end engineer', department: 'Programming', id: "2"},
{name: 'personal manager', department: 'Personal Management', id: "3"}
]
const JobType = new GraphQLObjectType({
name: 'Job',
fields: () => ({
id: {type: GraphQLID},
name: {type: GraphQLString},
department: {type: GraphQLString}
})
})
const RootQuery = new GraphQLObjectType({
name: 'RootQueryType',
fields: {
...,
job: {
type: JobType,
args: {
id: {type: GraphQLID}
},
resolve(parent, args) {
return _.find(jobs, {id: args.id})
}
}
}
})
再次运行http://localhost:4000/graphql, 界面如下所示:
可在Docs里看到新增了job查询类型, 执行查询, 结果如下所示:
关联PersonType和JobType
首先我们需要修改persons数据, 在里面加入jobId
var persons = [
{name: 'zhangsan', sex: 'male', age: 24, id: "1", jobId: "1"},
{name: 'lisi', sex: 'male', age: 28, id: "2", jobId: "1"},
{name: 'lili', sex: 'female', age: 31,id: "3", jobId: "2"}
]
然后, 在PersonType里加入job字段
const PersonType = new GraphQLObjectType({
name: 'Person',
fields: () => ({
...,
job: {
type: JobType,
resolve(parent, args) {
return _.find(jobs, {id: parent.jobId})
}
}
})
})
最后, 再次刷新http://localhost:4000/graphql, 界面如下所示:
GraphQLList
当我们想查询出所有的persons和jobs时, 需要引入一种新的类型GraphQLList, 代码如下所示:
const {
...,
GraphQLList
} = graphql
const RootQuery = new GraphQLObjectType({
name: 'RootQueryType',
fields: {
persons: {
type: new GraphQLList(PersonType),
resolve(parent, args) {
return persons
}
},
jobs: {
type: new GraphQLList(JobType),
resolve(parent, args) {
return jobs
}
},
}
})
刷新http://localhost:4000/graphql, 界面如下所示:
结语
现在数据较少, 可暂时以这种方式存于内存中, 可数据一旦增多, 便需要数据库进行存储了, 下一章将会为大家讲解Mongodb存储, 用线上直接存储方式, 避免搭建本地数据库, 今天先到这里, 谢谢大家观看