初始化項目
創建 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(</span></span> <span class="pl-s"> type Query {</span> <span class="pl-s"> hello: String</span> <span class="pl-s"> }</span> <span class="pl-s"><span class="pl-pds">
);
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 工具用於查詢的調試。
Graphiql 界面
測試 GraphQL 服務
前面定義的 schema 中包含一個 hello
字段,通過在前面的 Graphiql 中編輯查詢可請求該字段。
測試 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");
再次啟動服務並執行查詢,能夠看到返回了正確的數據。
返回數據的查詢