美文网首页
使用graphql创建API服务器

使用graphql创建API服务器

作者: 大地母亲忽悠着你 | 来源:发表于2018-01-11 15:19 被阅读0次
  • 依赖

    1. express
    2. express-graphql
    3. graphql
  • 创建服务器

    先要用express搭建服务器

    const express = require('express')
    const http = require('http')
    const R = require('ramda')
    
    const PORT = process.env.PORT ? process.env.PORT : 22333
    
    let app = express()
    app.get('/', (req, res) => {
      res.send('hello')
    })
    const httpServer = http.createServer(app)
    httpServer.listen(PORT, () => {
      console.log(`http://localhost:${PORT}/`)
    })
    

    要注意这里不要使用express的listen,方便以后对接https。

  • Schema

    新建schema.js的文件:

      const { buildSchema } = require('graphql')
    
      module.exports = buildSchema(`
        type Query{
          hello:String
        }
      `)
    
  • Resolver

    新建resolver.js

    module.exports = {
      hello: ()=>'hello'
    }
    
  • 在express中加入graphql中间件

    const express = require('express')
    const http = require('http')
    const R = require('ramda')
    
    const gqResolver = require('./graphql/resolver')
    const gqSchema = require('./graphql/schema')
    
    const PORT = process.env.PORT?process.env.PORT:22333
    
    let app = express()
    
    app.use('/graphql', expressGraphQL({
      schema: gqlSchema,
      rootValue: resolver,
      graphiql: true
    }))
    app.get('/', (req, res) => {
      res.send('hello')
    })
    
    const httpServer = http.createServer(app)
    httpServer.listen(PORT, () => {
      console.log(`http://localhost:${PORT}/`)
    })
    

    如果一切顺利的话启动服务器之后打开localhost:PORT/graphql , 听过会出现如下的画面,这时打开右上角的docs,就可以查询之前创建的API了。


    graphql.png
  • 测试

    接下来在左边的命令窗口中输入

    {hello}
    

    然后点击播放按钮就可以看到服务器返回的结果了


    graphql2.png

相关文章

网友评论

      本文标题:使用graphql创建API服务器

      本文链接:https://www.haomeiwen.com/subject/tenznxtx.html