使用 Apollo Server 实现一个简单的 GraphQL Server
一个简单的 Apollo Server 分为以下几个部分
- 服务器
- GraphQL 类型定义 typeDefs
- 数据源
- resolvers
特点: typeDefs 中定义的 type Query 中的字段 与 resolvers 中的 Query 返回值的字段是需要一一对应的!
const { ApolloServer, gql } = require('apollo-server')
// 类型定义
const typeDefs = gql`
type Book {
title: String
author: String
}
type Query {
books: [Book]
}
`
// 数据源
const books = [
{
title: 'Harry Potter and the Chamber of Secrets',
author: 'J.K. Rowling',
},
{
title: 'Jurassic Park',
author: 'Michael Crichton',
},
];
// resolver
const resolvers = {
Query: {
books: () => books,
}
}
// 服务
const server = new ApolloServer({typeDefs, resolvers})
server.listen().then( ({url}) => {
console.log(`🚀 Server ready at ${url}`);
})
启动服务
node ./index.js
在浏览器中打开http://localhost:4000/端口

架构类型
- 标量类型 Scalar(基本标量和自定义标量)
- 对象类型 Object
- 查询类型 Query
- 变异类型 Mutation
- 输入类型 Input
apollo-server API
顶层 API
- ApolloServer
- ApolloServer.listen
- ApolloServer.applyMiddleware
- ApolloServer.getMiddleware
- makeExecutableSchema
- addMockFunctionsToSchema(options)
- EngineReportingOptions
使用:
const {
ApolloServer,
makeExecutableSchema,
addMockFunctionsToSchema,
EngineReportingOptions
} = require('apollo-server-express');
ApolloServer - Options:
| 序号 | 参数 | 说明 |
|---|---|---|
| 1 | typeDefs | - |
| 2 | resolvers | - |
| 3 | context | - |
| 4 | logger | - |
| 5 | rootValue | - |
| 6 | mock | - |
| 7 | mockEntireSchema | - |
| 8 | schemaDirectives | - |
| 9 | introspection | - |
| 10 | playground | - |
| 11 | debug | - |
| 12 | validationRules | - |
| 13 | tracing, cacheControl | - |
| 14 | formatError, formatResponse | - |
| 15 | schema | - |
| 16 | subscriptions | - |
| 17 | engine | - |
| 18 | persistedQueries | - |
| 19 | cors | - |
| 20 | experimental_approximateDocumentStoreSizeMiB | - |