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

GraphQL
GraphQL系列教程:
- GraphQL的设计理念及安装配置
- Schema的基本使用
- GraphQL中的类型及类型间的关系
- 使用MongoDB作为数据存储层
- 在React中使用GraphQL
- 在AWS Appsync中使用GraphQL
- 如何在serverless中定义GraphQL API-不使用AppSync
- 如何在serverless中定义GraphQL API-使用AppSync并使用Lambda作为数据源
Schema做什么用的?
在GraphQL中,Schema的作用主要就是用来定义类型,以及类型之间的关系。比如:可以查询学生以及该学生选择的课程,在从学生链接到课程后,对于某项课程,又可以查询选择该课程的学生。也就说,这是一个图。
以学生为例,来定义一个Schema。添加schema/schema.js:
javascript
const graphql = require('graphql');
const {GraphQLObjectType, GraphQLString} = graphql;
const StudentType = new GraphQLObjectType({
name: 'Student',
fields: () => ({
id: {type: GraphQLString},
name: {type: GraphQLString},
address: {type: GraphQLString}
})
});
RootQuery
所谓RootQuery,其实就是GraphQL的查询入口。比如下面通过学生id进行查询:
javascript
const graphql = require('graphql');
const _ = require('lodash');
const {GraphQLObjectType, GraphQLString, GraphQLSchema} = graphql;
const students = [
{ id: '1', name: 'Lucas', address: '1 Fake Street' },
{ id: '2', name: 'Paul', address: '2 Fake Street' },
{ id: '3', name: 'Jess', address: '3 Fake Street' },
];
const StudentType = new GraphQLObjectType({
name: 'Student',
fields: () => ({
id: {type: GraphQLString},
name: {type: GraphQLString},
address: {type: GraphQLString}
})
});
const RootQuery = new GraphQLObjectType({
name: 'RootQueryType',
fields: {
student: {
type: StudentType,
args: {id: {type: GraphQLString}},
resolve(parent, args) {
return _.find(students, { id: args.id });
}
}
}
});
module.exports = new GraphQLSchema({
query: RootQuery
});
对应的app.js:
javascript
const express = require('express');
const {graphqlHTTP} = require('express-graphql');
const schema = require('./schema/schema');
const app = express();
app.use('/graphql', graphqlHTTP({
schema,
graphiql: true
}))
app.listen(4000, ()=>{
console.log('listening on 4000');
});
进行查询
这样就可以访问 http://localhost:4000/graphql 进行GraphQL的查询了:

GraphQL查询结果