GraphQL 是一种现代的数据查询语言,它提供了一种清晰和强大的方式来定义和查询 API。它既能够提高开发效率,又能够提供更好的应用程序性能和可扩展性。而 Koa2 是一个类似于 Express 的 Web 框架,它能够帮助我们快速地搭建一个高效的后端服务。本文将介绍如何使用 koa-graphql 来实现 GraphQL 服务并提供一些示例代码。
安装 koa-graphql
首先,我们需要全局安装 koa 和 koa-graphql。
npm install -g koa koa-graphql
基本使用
在我们开始编写 GraphQL 服务前,我们需要了解 GraphQL 的基本概念。在 GraphQL 中,我们定义了一个 schema,用于描述数据的结构和关系。schema 中包括了类型、查询、变量和操作等信息。
// www.javascriptcn.com code example
const { graphqlKoa, graphiqlKoa } = require('koa-graphql');
const Koa = require('koa');
const Router = require('koa-router');
const schema = require('./schema');
const app = new Koa();
const router = new Router();
router.post('/graphql', graphqlKoa({ schema: schema }));
router.get('/graphql', graphqlKoa({ schema: schema }));
router.get('/graphiql', graphiqlKoa({ endpointURL: '/graphql' }));
app.use(router.routes()).use(router.allowedMethods());
app.listen(3000, () => console.log('Server started on port 3000'));在上面的示例代码中,我们创建了一个 Koa 实例和一个 Koa Router 实例。然后,我们通过 graphqlKoa 和 graphiqlKoa 方法来创建 GraphQL 和 GraphiQL 中间件。接着,我们通过路由器将这些中间件绑定在不同的路由上。最后,我们在端口 3000 启动了 Koa 服务器。
构建 schema
接下来,我们需要定义我们的 schema。在本例中,我们将使用一个简单的 books 数据模型。我们的数据模型只包括书籍的 id、title 和 author 信息。
// www.javascriptcn.com code example
const {
GraphQLObjectType,
GraphQLSchema,
GraphQLID,
GraphQLString,
GraphQLList
} = require('graphql');
const books = [
{ id: '1', title: 'Harry Potter', author: 'J.K. Rowling' },
{ id: '2', title: 'The Lord of the Rings', author: 'J.R.R. Tolkien' }
];
const BookType = new GraphQLObjectType({
name: 'BookType',
fields: {
id: { type: GraphQLID },
title: { type: GraphQLString },
author: { type: GraphQLString },
}
});
const QueryType = new GraphQLObjectType({
name: 'QueryType',
fields: {
book: {
type: BookType,
args: { id: { type: GraphQLID } },
resolve(parentValue, args) {
const { id } = args;
return books.find((book) => book.id === id);
}
},
books: {
type: new GraphQLList(BookType),
resolve() {
return books;
}
}
}
});
const schema = new GraphQLSchema({
query: QueryType
});
module.exports = schema;在上面的代码中,我们定义了一个 BookType 类型和一个 QueryType 查询类型。然后,我们将 QueryType 挂载到我们的 GraphQL schema 上,并将其导出供其他文件使用。
使用 GraphiQL 查询数据库
我们已经完成了 schema 的定义,现在需要先验证查询是否正常。我们使用 GraphiQL 工具来验证 GraphQL schema 的查询和数据处理是否正确。
在浏览器中打开 http://localhost:3000/graphiql,你可以看到一个 UI 界面。在这个页面中,我们可以输入 GraphQL 查询语句并查看服务器返回的结果。
首先,我们输入以下查询语句:
{
book(id: "1") {
title
author
}
}这个查询将返回 id 为 1 的书籍的标题和作者信息。点击执行按钮后,我们将得到以下结果:
{
"data": {
"book": {
"title": "Harry Potter",
"author": "J.K. Rowling"
}
}
}接着,我们输入以下查询语句:
{
books {
title
author
}
}这个查询将返回所有书籍的标题和作者信息。执行按钮后,我们将得到以下结果:
// www.javascriptcn.com code example
{
"data": {
"books": [
{
"title": "Harry Potter",
"author": "J.K. Rowling"
},
{
"title": "The Lord of the Rings",
"author": "J.R.R. Tolkien"
}
]
}
}使用 GraphQL 查询数据库
现在我们已经完成了对 schema 的测试,并且了解了如何使用 GraphiQL 工具来测试查询语句。接下来,我们需要在应用程序中使用 GraphQL 来查询数据库。
// www.javascriptcn.com code example
router.post('/graphql', graphqlKoa(async (ctx) => {
try {
const query = ctx.request.body.query;
const result = await graphql(schema, query);
ctx.body = result;
} catch (err) {
console.log(err);
ctx.status = 400;
ctx.body = err;
}
}));在上面的代码中,我们使用 graphql 方法来执行查询语句。这个方法的第一个参数是我们的 schema,第二个参数是我们的查询语句。然后,我们将结果返回给客户端。
GraphQL 变量
在 GraphQL 中,我们可以使用变量来传递参数给查询语句。首先,我们需要在 schema 中定义我们的变量类型。
// www.javascriptcn.com code example
const { GraphQLNonNull, GraphQLInputObjectType } = require('graphql');
const BookInputType = new GraphQLInputObjectType({
name: 'BookInputType',
fields: {
id: { type: new GraphQLNonNull(GraphQLID)},
title: { type: new GraphQLNonNull(GraphQLString) },
author: { type: new GraphQLNonNull(GraphQLString) }
}
});
const MutationType = new GraphQLObjectType({
name: 'MutationType',
fields: {
addBook: {
type: BookType,
args: {
book: { type: new GraphQLNonNull(BookInputType) },
},
resolve(parentValue, args) {
const { id, title, author } = args.book;
const book = { id, title, author };
books.push(book);
return book;
}
},
}
});
const schema = new GraphQLSchema({
query: QueryType,
mutation: MutationType
});
module.exports = schema;在上面的代码中,我们定义了一个 BookInputType 类型,它包含了添加书籍时所需的参数。然后,我们定义一个 MutationType 变量来包含我们的修改操作。现在我们可以在查询语句中使用变量了。以下是一个添加书籍的查询示例:
mutation ($book: BookInputType!) {
addBook(book: $book) {
id
title
author
}
}{
"book": {
"id": "3",
"title": "The Hobbit",
"author": "J.R.R. Tolkien"
}
}最后
在这个简单的例子中,我们使用了 koa-graphql 和 GraphQL 和基于这些工具构建了一个有趣的、模块化的 Web 服务。希望这篇文章帮助你了解到一些有关 Koa2 和 GraphQL 的内容,并且能够开发出更加高效的 Web 服务。
来源:JavaScript中文网 ,转载请注明来源 https://www.javascriptcn.com/post/67bd8ddca231b2b7ed023a5f