Express.js 是一个广受欢迎的 Node.js Web 框架,通过使用它可以轻松构建服务器端应用程序。GraphQL 是一个用于构建 API 的查询语言,它使用类型系统来定义 API 的能力,并提供了一种更高效和强大的方式来获取您应用程序中的数据。在此文中,我们将探讨如何使用 Express.js 和 GraphQL 构建可扩展的 API。
设置 Express.js 服务器
首先,我们需要安装和设置 Express.js 服务器。我们将使用以下命令安装 Express.js 以及其他所需的依赖项:
npm install express express-graphql graphql
接下来,我们将创建一个名为 server.js 的文件,以设置 Express.js 服务器:
// www.javascriptcn.com code example
const express = require('express');
const { graphqlHTTP } = require('express-graphql');
const { buildSchema } = require('graphql');
const app = express();
const schema = buildSchema(`
type Query {
hello: String
}
`);
const rootValue = {
hello: () => 'Hello, World!'
};
app.use('/graphql', graphqlHTTP({
schema: schema,
rootValue: rootValue,
graphiql: true
}));
app.listen(4000, () => {
console.log('Express GraphQL Server Now Running On localhost:4000/graphql');
});其中,我们构建了一个作为根节点的查询对象,该对象具有一个名称为 hello 的字段。我们还定义了一个名为 rootValue 的对象,该对象定义了 hello 字段的解析函数,该函数将返回字符串“Hello, World!”。通过将 schema 和 rootValue 传递给 graphqlHTTP,我们将 GraphQL API 集成到了 Express.js 服务器中。
访问 localhost:4000/graphql,您应该能够看到 GraphQL Playground 工具,并且输入以下查询:
{
hello
}应该会返回以下响应:
{
"data": {
"hello": "Hello, World!"
}
}扩展 GraphQL API
现在我们已经有了基本的 GraphQL API,我们可以通过扩展它来实现更多的功能。让我们从一个简单的例子开始,我们将通过添加一个名为 person 的字段来扩展查询对象,该字段将返回一个人的姓名和年龄。
首先,我们将修改 schema,以包含一个名为 person 的对象类型,并包含姓名和年龄字段:
// www.javascriptcn.com code example
const schema = buildSchema(`
type Query {
hello: String,
person: Person
}
type Person {
name: String
age: Int
}
`);接下来,我们将定义一个名为 person 的根解析函数,该函数将返回一个包含姓名和年龄的对象:
const rootValue = {
hello: () => 'Hello, World!',
person: () => ({
name: 'John Doe',
age: 30
})
};现在,您可以输入以下查询并执行:
{
person {
name
age
}
}应该会返回以下响应:
{
"data": {
"person": {
"name": "John Doe",
"age": 30
}
}
}连接到数据库
大多数实际使用的 API 都需要从某种数据库中读取和写入数据。让我们探索如何集成 MongoDB 数据库与我们的 GraphQL API,以读取和写入人员数据。
首先,我们需要安装与 MongoDB 的 Node.js 驱动程序,使用以下命令安装 mongodb:
npm install mongodb
接下来,我们将导入 MongoDB 驱动程序并建立一个与数据库的连接:
// www.javascriptcn.com code example
const mongodb = require('mongodb');
const MongoClient = mongodb.MongoClient;
const uri = "mongodb://localhost:27017/mydb";
const client = new MongoClient(uri, { useNewUrlParser: true });
let database;
client.connect(err => {
if (err) {
console.log(err);
client.close();
return;
}
database = client.db('mydb');
});现在,我们已经连接到数据库。现在,我们将定义一个查询以获取所有人员,我们将查询 Mongo 数据库中的 persons 集合所包含的所有文档:
// www.javascriptcn.com code example
const rootValue = {
hello: () => 'Hello, World!',
person: () => ({
name: 'John Doe',
age: 30
}),
persons: async () => {
const persons = await database.collection('persons').find().toArray();
return persons;
}
};我们还定义了一个名为 persons 的字段作为查询类型。 当用户查询此字段时,我们将使用 MongoDB 驱动程序来检索 persons 集合中的所有文档并将其作为 JSON 对象返回。
现在,我们已经完成了我们的 GraphQL API,其中包含了 hello、person 和 persons 字段,persons 字段通过 MongoDB 驱动程序从表中检索所有人员数据。
以下是 server.js 中的完整代码:
// www.javascriptcn.com code example
const express = require('express');
const { graphqlHTTP } = require('express-graphql');
const { buildSchema } = require('graphql');
const mongodb = require('mongodb');
const app = express();
const MongoClient = mongodb.MongoClient;
const uri = "mongodb://localhost:27017/mydb";
const client = new MongoClient(uri, { useNewUrlParser: true });
let database;
client.connect(err => {
if (err) {
console.log(err);
client.close();
return;
}
database = client.db('mydb');
});
const schema = buildSchema(`
type Query {
hello: String,
person: Person,
persons: [Person]
}
type Person {
name: String
age: Int
}
`);
const rootValue = {
hello: () => 'Hello, World!',
person: () => ({
name: 'John Doe',
age: 30
}),
persons: async () => {
const persons = await database.collection('persons').find().toArray();
return persons;
}
};
app.use('/graphql', graphqlHTTP({
schema: schema,
rootValue: rootValue,
graphiql: true
}));
app.listen(4000, () => {
console.log('Express GraphQL Server Now Running On localhost:4000/graphql');
});通过实现此例,您应该能够更好地了解如何使用 Express.js 和 GraphQL 构建可扩展的 API。
来源:JavaScript中文网 ,转载请注明来源 https://www.javascriptcn.com/post/67da661fa941bf713426bc41