下面是一个示例代码,展示如何使用Node.js编写一个GraphQL解析器,将用户添加到MongoDB数据库中:
首先,你需要安装所需的依赖项。打开命令行工具,导航到项目目录,并运行以下命令:
npm install express graphql express-graphql mongoose
接下来,创建一个名为server.js
的文件,并将以下代码复制到文件中:
const express = require('express');
const { graphqlHTTP } = require('express-graphql');
const { buildSchema } = require('graphql');
const mongoose = require('mongoose');
// 连接到MongoDB数据库
mongoose.connect('mongodb://localhost/graphql-demo', {
useNewUrlParser: true,
useUnifiedTopology: true
});
mongoose.connection.once('open', () => {
console.log('Connected to database');
});
// 定义用户模型
const User = mongoose.model('User', {
name: String,
age: Number
});
// 定义GraphQL模式
const schema = buildSchema(`
type User {
id: ID,
name: String,
age: Int
}
type Query {
user(id: ID!): User
}
type Mutation {
addUser(name: String!, age: Int!): User
}
`);
// 定义GraphQL解析器
const root = {
user: async ({ id }) => {
return await User.findById(id);
},
addUser: async ({ name, age }) => {
const user = new User({ name, age });
await user.save();
return user;
}
};
// 创建Express应用程序
const app = express();
// 添加GraphQL中间件
app.use('/graphql', graphqlHTTP({
schema: schema,
rootValue: root,
graphiql: true
}));
// 启动服务器
app.listen(4000, () => {
console.log('Server is running on port 4000');
});
上面的代码首先导入所需的依赖项,然后连接到MongoDB数据库。接下来,定义了一个名为User
的模型,用于在数据库中存储用户信息。然后,使用buildSchema
函数定义了GraphQL模式,包括User
类型、Query
类型和Mutation
类型。最后,创建了一个GraphQL解析器,其中包含了处理user
查询和addUser
变异的函数。
最后,使用Express创建一个应用程序,并添加GraphQL中间件,将GraphQL请求路由到相应的解析器。最后,启动服务器并监听4000端口。
要运行此代码,确保你的MongoDB服务器正在运行,并且端口号为27017(默认情况下)。然后,在命令行中运行以下命令:
node server.js
现在,你可以在浏览器中访问http://localhost:4000/graphql
来使用GraphQL Playground进行测试和调试。你可以使用以下查询和变异来添加用户和获取用户:
查询用户:
query {
user(id: "用户的ID") {
id
name
age
}
}
添加用户:
mutation {
addUser(name: "用户的姓名", age: 20) {
id
name
age
}
}
尝试运行这些查询和变异,并检查MongoDB数据库中是否添加了用户数据。