概述
Apollo Server 通过 HTTP 执行 GraphQL 查询与变更。它提供符合规范的执行管线、用于缓存、追踪和生命周期钩子的插件系统,以及独立托管或接入现有 Node Web 框架的适配方式。服务端由 typeDefs 和 resolvers 构造,启动后才能接收流量。上下文按请求创建并传入 resolver,鉴权与 DataLoader 都应放在这里。Apollo Studio 上报需要通过环境变量显式开启,introspection 也可以独立关闭。
安装
npm install @apollo/server graphql
npm install @as-integrations/express5
graphql 是 peer 依赖。使用 Express 托管时,Apollo Server 5 把集成拆分为独立包:Express 5 使用 @as-integrations/express5,Express 4 使用 @as-integrations/express4。Apollo Server 5 需要当前的 Node.js LTS,旧的 apollo-server 包已停止维护,不应在新项目中使用。
核心 API
new ApolloServer:接收typeDefs、resolvers与插件,introspection等选项也在此配置。server.start:在接收流量前准备 schema 与插件,必须在启动阶段await。startStandaloneServer:启动独立 HTTP 服务,适合开发和简单部署,可传入上下文工厂。expressMiddleware:把同一个服务挂载到 Express 应用,注意从@as-integrations/express5导入。server.executeOperation:跳过 HTTP 直接执行查询,是集成测试 resolver 与错误处理的官方方式。
import { ApolloServer } from '@apollo/server';
import { startStandaloneServer } from '@apollo/server/standalone';
const server = new ApolloServer({ typeDefs, resolvers });
await server.start();
const { url } = await startStandaloneServer(server, {
listen: { port: 4000 },
context: async ({ req }) => ({ token: req.headers.authorization ?? '' }),
});
注意事项
在 start 之前调用 executeOperation 会失败。Express 中间件必须来自 @as-integrations 包,Apollo Server 5 的核心包不再导出 expressMiddleware。把上下文对象缓存在全局会串用请求状态。introspection 默认开启,若需要隐藏 schema,应在生产环境显式关闭。executeOperation 返回的 body 可能是单次结果,也可能是增量流,断言前要先判断 kind。
验证方式
用 executeOperation 执行查询,同时断言 data 与不存在 errors。把同一实例挂载到 Express,确认 POST /graphql 返回 JSON 与正确的内容类型。检查非法查询返回校验错误而不是 500,并验证上下文工厂能读取 Authorization 请求头。