如何将 Apollo 与 Deno 结合使用
Apollo Server 是一个 GraphQL 服务器,您可以在几分钟内设置好并与您现有的数据源(或 REST API)一起使用。然后,您可以将任何 GraphQL 客户端连接到它,以接收数据并利用 GraphQL 的优势,例如类型检查和高效获取。
我们将启动并运行一个简单的 Apollo 服务器,它将允许我们查询一些本地数据。我们只需要三个文件即可完成此操作
schema.ts
用于设置我们的数据模型resolvers.ts
用于设置我们将如何填充模式中的数据字段- 我们的
main.ts
,服务器将在其中启动
我们将从创建它们开始
touch schema.ts resolvers.ts main.ts
让我们逐步完成每个设置。
schema.ts 跳转到标题
我们的 schema.ts
文件描述了我们的数据。在本例中,我们的数据是恐龙列表。我们希望我们的用户能够获取每只恐龙的名称和简短描述。在 GraphQL 语言中,这意味着 Dinosaur
是我们的类型,而 name
和 description
是我们的字段。我们还可以定义每个字段的数据类型。在本例中,两者都是字符串。
这也是我们描述允许对数据进行的查询的地方,使用 GraphQL 中的特殊 Query 类型。我们有两个查询
dinosaurs
获取所有恐龙的列表dinosaur
接受恐龙的name
作为参数,并返回有关该类型恐龙的信息。
我们将所有这些导出到我们的 typeDefs
类型定义变量中
export const typeDefs = `
type Dinosaur {
name: String
description: String
}
type Query {
dinosaurs: [Dinosaur]
dinosaur(name: String): Dinosaur
}
`;
如果我们想要写入数据,这也是我们将描述用于执行此操作的 Mutation 的地方。Mutation 是您使用 GraphQL 写入数据的方式。因为我们在这里使用静态数据集,所以我们不会写入任何内容。
resolvers.ts 跳转到标题
解析器负责填充每个查询的数据。在这里,我们有恐龙列表,所有解析器将要做的是 a) 如果用户请求 dinosaurs
查询,则将整个列表传递给客户端,或者 b) 如果用户请求 dinosaur
查询,则仅传递一个。
const dinosaurs = [
{
name: "Aardonyx",
description: "An early stage in the evolution of sauropods.",
},
{
name: "Abelisaurus",
description: '"Abel\'s lizard" has been reconstructed from a single skull.',
},
];
export const resolvers = {
Query: {
dinosaurs: () => dinosaurs,
dinosaur: (_: any, args: any) => {
return dinosaurs.find((dinosaur) => dinosaur.name === args.name);
},
},
};
对于后者,我们将来自客户端的参数传递到函数中,以将名称与数据集中的名称匹配。
main.ts 跳转到标题
在我们的 main.ts
中,我们将导入 ApolloServer
以及 graphql
和来自模式的 typeDefs
以及我们的解析器
import { ApolloServer } from "npm:@apollo/server@^4.1";
import { startStandaloneServer } from "npm:@apollo/server@4.1/standalone";
import { graphql } from "npm:graphql@16.6";
import { typeDefs } from "./schema.ts";
import { resolvers } from "./resolvers.ts";
const server = new ApolloServer({
typeDefs,
resolvers,
});
const { url } = await startStandaloneServer(server, {
listen: { port: 8000 },
});
console.log(`Server running on: ${url}`);
我们将 typeDefs
和 resolvers
传递给 ApolloServer
以启动一个新服务器。最后,startStandaloneServer
是一个帮助函数,用于快速启动并运行服务器。
运行服务器 跳转到标题
现在剩下的就是运行服务器
deno run --allow-net --allow-read --allow-env main.ts
您应该在终端中看到 Server running on: 127.0.0.1:8000
。如果您转到该地址,您将看到 Apollo 沙箱,我们可以在其中输入我们的 dinosaurs
查询
query {
dinosaurs {
name
description
}
}
这将返回我们的数据集
{
"data": {
"dinosaurs": [
{
"name": "Aardonyx",
"description": "An early stage in the evolution of sauropods."
},
{
"name": "Abelisaurus",
"description": "\"Abel's lizard\" has been reconstructed from a single skull."
}
]
}
}
或者,如果我们只想要一个 dinosaur
query {
dinosaur(name:"Aardonyx") {
name
description
}
}
这将返回
{
"data": {
"dinosaur": {
"name": "Aardonyx",
"description": "An early stage in the evolution of sauropods."
}
}
}
太棒了!