[GraphQL] Serve a GraphQL Schema as Middleware in Express


If we have a GraphQL Schema expressed in terms of JavaScript, then we have a convenient package available to us that let’s us easily serve up our schema on any endpoint in an Express Server. In this video, we’ll use theexpress-graphqlpackage to serve up our GraphQL Schema as middleware, and also learn how to enable the GraphiQL tool in order to query our GraphQL Schema.

Install:

yard add express express-graphql graphql

const express   = require('express');
const graphqlHttp = require('express-graphql');

const server = express();
const port   = process.env.PORT || 3000;

const { graphql, buildSchema } = require('graphql');

const schema = buildSchema(`
    type Video {
        id: ID,
        title: String,
        duration: Int,
        watched: Boolean
    }
    
    type Query {
        video: Video,
        videos: [Video]
    }
    
    type Schema{
        query: Query
    }
`);

const videos = [
    {
        id       : '1',
        title    : 'react',
        duration : 180,
        watched  : true
    },
    {
        id       : '2',
        title    : 'relay',
        duration : 230,
        watched  : false
    }
];

const resolvers = {
    video  : () => ({
        id       : '1',
        title    : 'bar',
        duration : 180,
        watched  : true
    }),
    videos : () => videos
};

server.use('/graphql', graphqlHttp({
                                     schema,
                                     graphiql  : true, // use graphiql interface
                                     rootValue : resolvers
                                 }));

server.listen(port, () => {
    console.log(`Listening on http`)
})

We use 'graphql' middleware, once we visit http://localhost:3000/graphql and enter the query:

长按二维码向我转账

受苹果公司新规定影响,微信 iOS 版的赞赏功能被关闭,可通过二维码转账支持公众号。

    阅读
    好看
    已推荐到看一看
    你的朋友可以在“发现”-“看一看”看到你认为好看的文章。
    已取消,“好看”想法已同步删除
    已推荐到看一看 和朋友分享想法
    最多200字,当前共 发送

    已发送

    朋友将在看一看看到

    确定
    分享你的想法...
    取消

    分享想法到看一看

    确定
    最多200字,当前共

    发送中

    网络异常,请稍后重试

    微信扫一扫
    关注该公众号





    联系我们

    欢迎来到TinyMind。

    关于TinyMind的内容或商务合作、网站建议,举报不良信息等均可联系我们。

    TinyMind客服邮箱:support@tinymind.net.cn