GraphQL教程二:Schema


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

GraphQL
GraphQL

GraphQL系列教程:

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查询结果
GraphQL查询结果


文章作者: 逻思
版权声明: 本博客所有文章除特別声明外,均采用 CC BY-NC-ND 4.0 许可协议。转载请注明来源 逻思 !