Koa + GraphQL 示例
初始化项目创建 $ mkdir graphql-example && cd $_ $ yarn init -y 安装依赖使用 koa-graphql 配合 koa-mount 两个 npm 模块来使用 GraphQL。同时需要安装 graphql 模块来创建需要使用的 schema。 SRE实战 互联网时代守护先锋,助力企业售后服务体系运筹帷幄!一键直达领取阿里云限量特价优惠。$ yarn add koa graphql koa-graphql koa-mount server安装 server.js const Koa = require("koa"); const app = new Koa(); app.use(async ctx => { ctx.body = "Hello World"; }); app.listen(3000); console.log("server started at http://localhost:3000"); 通过 Node.js 启动后便可访问到页面了。 $ node server.js server started at http://localhost:3000 创建 schemaGraphQL 需要一个 schema 来初始化,创建 $ mkdir graphql $ touch graphql/schema.js schema.js const { buildSchema } = require('graphql'); const schema = buildSchema(` type Query { hello: String } `); module.exports = schema; 启动 GraphQL 服务将上面的 schema 传入 server.js const Koa = require("koa"); const mount = require("koa-mount"); const graphqlHTTP = require("koa-graphql"); const schema = require("./graphql/schema"); const app = new Koa(); app.use( mount( "/graphql", graphqlHTTP({ schema: schema, graphiql: true }) ) ); app.listen(3000); console.log("server started at http://localhost:3000"); 再次启动 Graphiql 界面 测试 GraphQL 服务前面定义的 schema 中包含一个 测试 Query 可以看到返回的数据为 添加 resolver在 graphql/resolver.js module.exports = { hello: () => "Hello world!" }; 更新我们创建 GraphQL 服务的代码,将 resolver 传入: server.js const Koa = require("koa"); const mount = require("koa-mount"); const graphqlHTTP = require("koa-graphql"); const schema = require("./graphql/schema"); + const root = require("./graphql/resolver"); const app = new Koa(); app.use( mount( "/graphql", graphqlHTTP({ schema: schema, + rootValue: root, graphiql: true }) ) ); app.listen(3000); console.log("server started at http://localhost:3000"); 再次启动服务并执行查询,能够看到返回了正确的数据。 返回数据的查询 相关资源 |

更多精彩