推荐答案
// www.javascriptcn.com code example
const { ApolloServer, gql } = require('apollo-server');
// 定义类型
const typeDefs = gql`
type Query {
hello: String
}
`;
// 定义解析器
const resolvers = {
Query: {
hello: () => 'Hello, world!',
},
};
// 创建 Apollo Server 实例
const server = new ApolloServer({ typeDefs, resolvers });
// 启动服务器
server.listen().then(({ url }) => {
console.log(`🚀 Server ready at ${url}`);
});本题详细解读
1. 安装依赖
首先,你需要安装 apollo-server 包,它是构建 GraphQL 服务器的核心库。
npm install apollo-server graphql
2. 定义类型 (Type Definitions)
在 GraphQL 中,类型定义(Type Definitions)是描述数据的结构。使用 gql 模板字符串来定义类型。
const typeDefs = gql`
type Query {
hello: String
}
`;在这个例子中,我们定义了一个 Query 类型,其中包含一个 hello 字段,返回一个字符串。
3. 定义解析器 (Resolvers)
解析器是实际处理请求并返回数据的函数。每个字段都有一个对应的解析器。
const resolvers = {
Query: {
hello: () => 'Hello, world!',
},
};在这个例子中,hello 字段的解析器返回字符串 'Hello, world!'。
4. 创建 Apollo Server 实例
使用 ApolloServer 类创建一个新的服务器实例,并传入类型定义和解析器。
const server = new ApolloServer({ typeDefs, resolvers });5. 启动服务器
最后,调用 listen 方法启动服务器,并监听指定的端口。
server.listen().then(({ url }) => {
console.log(`🚀 Server ready at ${url}`);
});服务器启动后,你可以在浏览器中访问 http://localhost:4000 来使用 GraphQL Playground 进行查询。