# @as-integrations/fastify 中文文档

规范地址：https://npmcn.com/package/%40as-integrations/fastify/

版本：3\.1\.0
npm 元数据更新时间：2026-01-22T17:35:23.299Z
中文译文更新时间：2026-11-06T21:56:49.776Z
软件包许可：MIT

本文由上游 README 翻译，可能存在偏差，请结合原文核对 API、命令与配置。版权与许可归原作者所有。

原始 npm 页面：https://www.npmjs.com/package/%40as-integrations/fastify
原文对照：https://npmcn.com/package/%40as-integrations/fastify/?lang=original
项目主页：https://github.com/apollo-server-integrations/apollo-server-integration-fastify/blob/main/readme.md
源码仓库：https://github.com/apollo-server-integrations/apollo-server-integration-fastify

## 关键信息（来自 npm 元数据）

- 包体积（解压后）：30.4 kB，33 个文件
- 模块格式：ESM + CJS
- TypeScript 类型：包内自带
- Node.js 要求：\>=20
- 运行依赖：1 个
- peer 依赖：fastify ^5\.3\.0，@apollo/server ^4\.0\.0 \|\| ^5\.0\.0
- 首次发布：2022-09-30T15:52:44.055Z
- 最新版本发布：2025-10-10T19:20:23.131Z
- 近 30 天下载量：1316099（2026-10-07 至 2026-11-05，npm 官方下载统计）
- 已发布版本数：15（近 12 个月 0 个）

## 中文简介

Apollo 服务器集成, 用于快取

## 安装

```sh
npm install @as-integrations/fastify
```

也可以使用：`pnpm add @as-integrations/fastify`、`yarn add @as-integrations/fastify`、`bun add @as-integrations/fastify`

## README

[![Apollo Server](https://avatars.githubusercontent.com/u/17189275?s=200)](https://www.apollographql.com/) [![Fastify](https://avatars.githubusercontent.com/u/24939410?s=200)](https://www.fastify.io/)

[![NPM version](https://badge.fury.io/js/@as-integrations%2Ffastify.svg)](https://www.npmjs.com/package/@as-integrations/fastify) [![NPM downloads](https://img.shields.io/npm/dm/@as-integrations/fastify.svg?style=flat)](https://www.npmjs.com/package/@as-integrations/fastify)

# 阿波罗服务器集成以快速化

## **导言**

**阿波罗服务器集成,用于快取.**

这是一个简单的软件包,可以方便的将自己的Fastify服务器执行与阿波罗服务器实例连接.

## **所需资源**

-   **[节点.js v20](https://nodejs.org/)** 或稍后时间
-   **[速报 v 5.3.0](https://www.fastify.io/)** 或稍后时间
-   **[图QL.js v16](https://graphql.org/graphql-js/)** 或稍后时间
-   **[阿波罗服务器 v4](https://www.apollographql.com/docs/apollo-server/)** 或稍后时间

## **安装**

```bash
npm install @as-integrations/fastify @apollo/server graphql fastify
```

## **使用量**

设置 [快捷化](https://www.fastify.io/) 打开 [阿波罗服务器](https://www.apollographql.com/docs/apollo-server/) 就像你通常会,然后通过使用 `fastifyApollo` 插件 :

```typescript
import Fastify from "fastify";
import { ApolloServer, BaseContext } from "@apollo/server";
import fastifyApollo, { fastifyApolloDrainPlugin } from "@as-integrations/fastify";
// ...

const fastify = Fastify();

const apollo = new ApolloServer<BaseContext>({
  typeDefs,
  resolvers,
  plugins: [fastifyApolloDrainPlugin(fastify)],
});

await apollo.start();

// ...

await fastify.register(fastifyApollo(apollo));
```

说明: **你必须打电话等待 `apollo.start()` 在使用整合之前.**

或者您可以使用导出函数 `fastifyApolloHandler` 可以传入任何 [快速路由处理器](https://www.fastify.io/docs/latest/Reference/Routes/)。 。 。 . 这使得您可以明确设置所有路径选项,比如URL路径和被接受的方法.

实例如下:

```typescript
import { fastifyApolloHandler } from "@as-integrations/fastify";

// ... setup Fastify & Apollo

fastify.post("/graphql", fastifyApolloHandler(apollo));
// OR
fastify.get("/api", fastifyApolloHandler(apollo));
// OR
fastify.route({
  url: "/graphql",
  method: ["POST", "OPTIONS"],
  handler: fastifyApolloHandler(apollo),
});
```

请看 [实例](https://github.com/apollo-server-integrations/apollo-server-integration-fastify/tree/main/example)。 。 。 .

## **A. 背景情况**

阿波罗服务器 v4 已将上下文设置移出 `ApolloServer` 建筑师.

定义您自己的上下文函数并将其传递到 `context` 选项。 此函数接受两个参数 - 请求和答复 。 它们是一类的 `FastifyRequest` 财务报告和审定财务报表 `FastifyReply` 页:1 无论从函数中返回到什么 都会传给 `context` 在你的解决者中争论.

例如:

```typescript
import { ApolloServer } from "@apollo/server";

import fastifyApollo, {
  fastifyApolloHandler,
  ApolloFastifyContextFunction,
} from "@as-integrations/fastify";
// ...

interface MyContext {
  authorization: JWTPayload | false;
}

const apollo = new ApolloServer<MyContext>(...);

const myContextFunction: ApolloFastifyContextFunction<MyContext> = async (request, reply) => ({
  authorization: await isAuthorized(request.headers.authorization),
});

await fastify.register(fastifyApollo(apollo), {
  context: myContextFunction,
});

// OR

await fastify.post("/graphql", fastifyApolloHandler(apollo, {
  context: myContextFunction,
}));
```

```ts
// Access the context in your resolvers
export const resolvers = {
  Query: {
    helloWorld: (parent, args, context, info) => {
      if (!context.authorization) {
        throw new Error("Not authorized");
      }

      return "Hello world :)";
    },
  },
};
```

## **API 密码**

除在 `ApolloServer` 举个例子.

### `fastifyApollo`

```typescript
function fastifyApollo<Context extends BaseContext = BaseContext>(
  apollo: ApolloServer<Context>,
): FastifyPluginAsync<ApolloFastifyPluginOptions<Context>>;
```

### `fastifyApolloHandler`

```typescript
function fastifyApolloHandler<Context extends BaseContext = BaseContext>(
  apollo: ApolloServer<Context>,
  options?: ApolloFastifyHandlerOptions<Context>,
): RouteHandlerMethod;
```

### `ApolloFastifyContextFunction`

```typescript
type ApolloFastifyContextFunction<Context> = (
  request: FastifyRequest,
  reply: FastifyReply,
) => Promise<Context>;
```

### `ApolloFastifyHandlerOptions`

```typescript
interface ApolloFastifyHandlerOptions<Context extends BaseContext = BaseContext> {
  context?: ApolloFastifyContextFunction<Context>; // default: async () => ({})
}
```

### `ApolloFastifyPluginOptions`

```typescript
interface ApolloFastifyPluginOptions<Context extends BaseContext = BaseContext>
  extends ApolloFastifyHandlerOptions<Context> {
  path?: string; // default: "/graphql"
  method?: HTTPMethod | HTTPMethod[]; // default: ["GET", "POST", "OPTIONS"]
}
```

[`HTTPMethod`](https://www.fastify.io/docs/latest/Reference/TypeScript/#fastifyhttpmethods) 从 Fastify 中导出.

## **HTTPS/HTTP2 高频**

所有功能和类型都允许您通过或推断 a `Server` 从快取.

## **贡献者**

-   奥利弗·普卢默(英语:Oliver Plummer)[椭圆形](https://github.com/olyop)(中文(简体) )
-   特雷弗·舍尔(英语:Trevor Scheer (film))[偷车手](https://github.com/trevor-scheer)(中文(简体) )

## 常见问题

### @as-integrations/fastify 是什么？

Apollo 服务器集成, 用于快取

### 如何安装 @as-integrations/fastify？

在项目目录运行 npm install @as-integrations/fastify，或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖：fastify（^5\.3\.0）、@apollo/server（^4\.0\.0 \|\| ^5\.0\.0）。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖，Yarn 需要手动安装。

### @as-integrations/fastify 支持 TypeScript 吗？

支持。包内自带 TypeScript 类型声明（package\.json 声明了 types 入口），安装后即可获得类型提示，无需再安装 @types 包。

### @as-integrations/fastify 支持 ESM 还是 CommonJS？

同时提供 ES Module 与 CommonJS 入口，import 和 require\(\) 都可以使用，打包工具会自动选择合适的版本。

### @as-integrations/fastify 需要什么版本的 Node\.js？

package\.json 的 engines 字段要求 Node\.js \>=20。版本不符时 npm 默认只给出警告，开启 engine-strict 后会拒绝安装。

### @as-integrations/fastify 可以商用吗？

@as-integrations/fastify 使用 MIT 许可。宽松许可：允许商业使用、修改和再分发，通常只需在分发时保留原版权与许可声明。以上为概括，不构成法律意见，请以许可原文为准。

### @as-integrations/fastify 的下载量有多少？

根据 npm 官方下载统计，@as-integrations/fastify 在 2026/10/07 – 2026/11/05 这 30 天内被下载 1,316,099 次，日均约 43,870 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入，适合横向比较热度，不能直接等同于使用人数。

### @as-integrations/fastify 还在维护吗？

最新版本 3\.1\.0 发布于 2025/10/11（1\.1 年前）；至今共发布 15 个版本，其中过去 12 个月发布了 0 个；首次发布于 2022/09/30。发布频率只是参考信号：功能稳定的工具可能很少需要更新，建议结合源码仓库的 issue 和提交记录判断。

