GraphQL 是一种由 Facebook 开发的查询语言和运行时环境,用于 API 的查询和数据操作。在前端开发中,GraphQL 能够更好地满足客户端的需求,并且可以减少网络传输的数据量,提高应用的性能。在本文中,我们将介绍如何在 Node.js 和 Express 中使用 GraphQL 查询和修改数据。
安装依赖
在使用 GraphQL 之前,需要安装一些必要的依赖:
npm install graphql express-graphql
其中,graphql 是 GraphQL 的核心库,express-graphql 是在 Express 中使用 GraphQL 的中间件。
创建 GraphQL Schema
在使用 GraphQL 查询和修改数据之前,需要先创建一个 GraphQL Schema。Schema 定义了数据的类型和查询方式,可以理解为是一份数据字典。
在本文中,我们将创建一个简单的 User 类型,包含 id 和 name 两个字段,然后定义两个查询方式:getUserById 和 getAllUsers。代码如下:
// www.javascriptcn.com code example
const { GraphQLObjectType, GraphQLString, GraphQLList, GraphQLNonNull, GraphQLSchema } = require('graphql');
// 定义 User 类型
const UserType = new GraphQLObjectType({
name: 'User',
fields: () => ({
id: { type: GraphQLString },
name: { type: GraphQLString }
})
});
// 定义查询方式
const RootQuery = new GraphQLObjectType({
name: 'RootQueryType',
fields: {
getUserById: {
type: UserType,
args: {
id: { type: GraphQLNonNull(GraphQLString) }
},
resolve: (parent, args) => {
// 根据 id 查询用户
const user = { id: args.id, name: '张三' };
return user;
}
},
getAllUsers: {
type: new GraphQLList(UserType),
resolve: () => {
// 查询所有用户
const users = [{ id: '1', name: '张三' }, { id: '2', name: '李四' }];
return users;
}
}
}
});
// 定义 Mutation
const Mutation = new GraphQLObjectType({
name: 'Mutation',
fields: {
addUser: {
type: UserType,
args: {
name: { type: GraphQLNonNull(GraphQLString) }
},
resolve: (parent, args) => {
// 添加用户
const user = { id: '3', name: args.name };
return user;
}
}
}
});
// 导出 Schema
module.exports = new GraphQLSchema({
query: RootQuery,
mutation: Mutation
});在上面的代码中,我们定义了 User 类型,包含 id 和 name 两个字段。然后定义了两个查询方式:getUserById 和 getAllUsers,分别用于查询单个用户和所有用户。在查询方式的 resolve 函数中,我们可以编写实际的数据查询逻辑。
另外,我们还定义了一个 Mutation,用于新增用户。Mutation 是用于修改数据的,与查询方式不同,它需要定义 args 参数和 resolve 函数,用于接收并处理客户端传递的参数。
最后,我们将定义好的 Schema 导出,后面在 Express 中使用。
在 Express 中使用 GraphQL
在 Express 中使用 GraphQL 需要使用 express-graphql 中间件。在 app.js 中添加如下代码:
// www.javascriptcn.com code example
const express = require('express');
const { graphqlHTTP } = require('express-graphql');
const schema = require('./schema');
const app = express();
app.use('/graphql', graphqlHTTP({
schema,
graphiql: true
}));
app.listen(3000, () => {
console.log('Server started on port 3000');
});在上面的代码中,我们使用 graphqlHTTP 中间件创建了一个 GraphQL 服务,并将 Schema 和 graphiql: true 选项传递给中间件。graphiql 是一个可交互的 GraphQL 查询工具,可以在浏览器中方便地测试和调试 GraphQL 接口。
测试 GraphQL 接口
在浏览器中打开 http://localhost:3000/graphql,即可进入 graphiql 工具。在左侧的查询面板中输入如下查询语句:
query {
getUserById(id: "1") {
id
name
}
}点击运行按钮,即可在右侧的结果面板中看到查询结果:
{
"data": {
"getUserById": {
"id": "1",
"name": "张三"
}
}
}这个查询语句用于查询 id 为 1 的用户信息。我们在 getUserById 的 resolve 函数中返回了一个固定的用户信息,因此查询结果也是固定的。
接下来,我们再测试一下查询所有用户的接口,查询语句如下:
query {
getAllUsers {
id
name
}
}查询结果如下:
// www.javascriptcn.com code example
{
"data": {
"getAllUsers": [
{
"id": "1",
"name": "张三"
},
{
"id": "2",
"name": "李四"
}
]
}
}最后,我们再测试一下新增用户的接口,查询语句如下:
mutation {
addUser(name: "王五") {
id
name
}
}查询结果如下:
{
"data": {
"addUser": {
"id": "3",
"name": "王五"
}
}
}在这个查询语句中,我们使用了 mutation 关键字,表明这是一个修改数据的操作。在 addUser 的 resolve 函数中,我们返回了一个固定的用户信息。
至此,我们已经完成了在 Node.js 和 Express 中使用 GraphQL 查询和修改数据的教程。在实际开发中,可以根据需求来定义更复杂的 Schema 和查询方式,提高应用的性能和效率。
来源:JavaScript中文网 ,转载请注明来源 https://www.javascriptcn.com/post/67d4e090a941bf713491ae9c