Koa + GraphQL 示例

栏目: Node.js · 发布时间: 5年前

内容简介:创建使用安装

初始化项目

创建 graphql-example 文件夹进入后初始化一个 package.json 文件。

$ mkdir graphql-example && cd $_
$ yarn init -y

安装依赖

使用 koa-graphql 配合 koa-mount 两个 npm 模块来使用 GraphQL。同时需要安装 graphql 模块来创建需要使用的 schema。

$ yarn add koa graphql koa-graphql koa-mount

server

安装 koa 后,创建 server.js 实现一个简单的服务端。

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

创建 schema

GraphQL 需要一个 schema 来初始化,创建 graphql 目录并在其中创建 schema.js 文件,

$ mkdir graphql
$ touch graphql/schema.js

schema.js

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

const schema = buildSchema(`
 type Query {
   hello: String
 }
`);

module.exports = schema;

启动 GraphQL 服务

将上面的 schema 传入 koa-graphql 然后通过 koa-mount 将其作为中间件启动,便可开启 GraphQL 服务。

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");

再次启动 server.js 并访问 http://localhost:3000/graphql 可看到一个可视化的 GraphQL 界面。该界面为 GraphQL 内置的 Graphiql 工具用于查询的调试。

Koa + GraphQL 示例

Graphiql 界面

测试 GraphQL 服务

前面定义的 schema 中包含一个 hello 字段,通过在前面的 Graphiql 中编辑查询可请求该字段。

Koa + GraphQL 示例

测试 Query

可以看到返回的数据为 null ,这是因为我们还没有为该字段定义 resolver,即告诉 GraphQL 如何以及从哪里返回该数据。

添加 resolver

graphql 目录创建 resolver.js 文件,为 hello 字段指定数据的返回逻辑。

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");

再次启动服务并执行查询,能够看到返回了正确的数据。

Koa + GraphQL 示例

返回数据的查询


以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

刷新

刷新

[美] 萨提亚·纳德拉 / 陈召强、杨洋 / 中信出版集团 / 2018-1 / 58

《刷新:重新发现商业与未来》是微软CEO萨提亚•纳德拉首部作品。 互联网时代的霸主微软,曾经错失了一系列的创新机会。但是在智能时代,这家科技公司上演了一次出人意料的“大象跳舞”。2017年,微软的市值已经超过6000亿美元,在科技公司中仅次于苹果和谷歌,高于亚马逊和脸谱网。除了传统上微软一直占有竞争优势的软件领域,在云计算、人工智能等领域,微软也获得强大的竞争力。通过收购领英,微软还进入社交......一起来看看 《刷新》 这本书的介绍吧!

随机密码生成器
随机密码生成器

多种字符组合密码

Base64 编码/解码
Base64 编码/解码

Base64 编码/解码

html转js在线工具
html转js在线工具

html转js在线工具