在前面介绍了GraphQL的设计理念及安装配置及Schema的基本使用,下面来说说GraphQL中的类型。

GraphQL教程
GraphQL系列教程:
- GraphQL的设计理念及安装配置
- Schema的基本使用
- GraphQL中的类型及类型间的关系
- 使用MongoDB作为数据存储层
- 在React中使用GraphQL
- 在AWS Appsync中使用GraphQL
- 如何在serverless中定义GraphQL API-不使用AppSync
- 如何在serverless中定义GraphQL API-使用AppSync并使用Lambda作为数据源
基本类型:GraphQLID
在GraphQL中,GraphQLID的作用是来标识一条数据的。对应的数据可以是数字或者字符串。比如StudentType的类型定义可以为:
javascript
const {GraphQLObjectType, GraphQLString, GraphQLSchema, GraphQLID} = graphql;
const StudentType = new GraphQLObjectType({
name: 'Student',
fields: () => ({
id: {type: GraphQLID},
name: {type: GraphQLString},
address: {type: GraphQLString}
})
});
定义Student和Tutor之间的关系
测试数据
javascript
var students = [
{ id: '1', name: 'Lucas', address: '1 Fake Street', tutorid: "1" },
{ id: '2', name: 'Paul', address: '2 Fake Street' , tutorid: "2"},
{ id: '3', name: 'Jess', address: '3 Fake Street', tutorid: "3" },
{ id: '4', name: 'Tom', address: '4 Fake Street', tutorid: "4" },
{ id: '5', name: 'Ned', address: '5 Fake Street', tutorid: "2" },
{ id: '6', name: 'Dan', address: '6 Fake Street', tutorid: "2" },
{ id: '7', name: 'Luke', address: '7 Fake Street', tutorid: "2" },
{ id: '8', name: 'Lucy', address: '8 Fake Street', tutorid: "3" },
{ id: '9', name: 'Chole', address: '9 Fake Street', tutorid: "3" },
{ id: '10', name: 'Amy', address: '10 Fake Street', tutorid: "4" },
];
var tutors = [
{id: '1', name: 'Dr Kerridge'},
{id: '2', name: 'Prof Kennedy'},
{id: '3', name: 'Prof Harding'},
{id: '4', name: 'Dr Tang'},
];
更新RootQuery
一旦添加了多个类型,就需要在RootQuery中声明多个入口:
javascript
const RootQuery = new GraphQLObjectType({
name: 'RootQueryType',
fields: {
student: {
type: StudentType,
args: {id: {type: GraphQLID}},
resolve(parent, args) {
return _.find(students, { id: args.id });
}
},
tutor: {
type: TutorType,
args: {id: {type: GraphQLID}},
resolve(parent, args) {
return _.find(tutors, { id: args.id });
}
}
}
});
定义Student到Tutor的一对一关系
javascript
const StudentType = new GraphQLObjectType({
name: 'Student',
fields: () => ({
id: {type: GraphQLID},
name: {type: GraphQLString},
address: {type: GraphQLString},
tutor: {
type: TutorType,
resolve(parent, args) {
return _.find(tutors, {id: parent.tutorid})
}
}
})
});
定义由Tutor到Student之间的一对多关系
javascript
const TutorType = new GraphQLObjectType({
name: 'Tutor',
fields: () => ({
id: {type: GraphQLID},
name: {type: GraphQLString},
students: {
type: new GraphQLList(StudentType),
resolve(parent, args) {
return _.filter(students, {tutorid: parent.id})
}
}
})
});
这样就可以进行如下查询了:

GraphQL教程
支持更多的Root Query
可以增加students这个Root Query:
javascript
students: {
type: new GraphQLList(StudentType),
resolve(parent, args) {
return students;
}
}
这样就可以进行如下的查询:

GraphQL教程
同理,可以定义tutors这个Root Query:
javascript
tutors: {
type: new GraphQLList(TutorType),
resolve(parent, args) {
return tutors;
}
}
这样就可以进行如下GraphQL查询:
json
{
tutors {
name
students {
name
}
}
}
至此,我们已经支持4种不同的Root Query了:

GraphQL教程