# 用 Node.js 构建 GraphQL API

来源：https://docs.nestjs.com/tutorials/graphql-api

使用 NestJS、Apollo 和 PostgreSQL，在 Node.js 和 TypeScript 中构建 GraphQL API：批量解析器、登录、错误码和订阅。

该 API 服务于一个博客：用户撰写文章，在发布之前把它们保存为草稿，并互相评论对方的文章。为此搭起一个 GraphQL 服务器只需几分钟，而大多数示例到此为止。本教程把时间花在它们略过的部分：嵌套字段引发的 N+1 查询、通过没人想到的字段泄露出去的草稿、客户端无法区分的错误，以及跳过了每个 HTTP 请求都要经历的检查的 WebSocket。

完成之后，这个 API 将能够：

- 从 TypeScript 类生成 schema（[代码优先](/graphql/quick-start#code-first)），由 Node 适配器上的 Apollo Server 提供服务。
- 通过 [Drizzle](/data/drizzle) 把用户、文章和评论保存在 PostgreSQL 中，并用游标分页浏览文章。
- 批量加载嵌套字段，使 SQL 查询数量不随列表长度增长。
- 使用变更和 [`@nestjs/authentication`](/security/authentication) 让用户登录：访问令牌，以及会轮换的刷新令牌。
- 在所有路径上都只向作者本人展示草稿，并且只向邮箱所有者展示该邮箱地址。
- 用客户端可以据以行动的代码作答（`UNAUTHENTICATED`、`FORBIDDEN`、`BAD_USER_INPUT`、`NOT_FOUND`），并在生产环境中隐藏意外错误。
- 通过 `graphql-ws` 向已登录的订阅者推送新评论。
- 在针对 PostgreSQL 的测试中、通过 HTTP 和真实 WebSocket 验证这些行为。

以下是各项操作，以及添加它们的小节：

| 操作 | 小节 |
| --- | --- |
| `posts`、`post`、`createPost`、`updatePost`、`publishPost`、`addComment` | [读写文章](/tutorials/graphql-api#read-and-write-posts) |
| `Post.author`、`Post.comments`、`User.posts`、`User.email`、`me` | [用 DataLoader 批量加载嵌套字段](/tutorials/graphql-api#batch-nested-fields-with-dataloader) |
| `signUp`、`signIn`、`refreshToken` | [用变更让用户登录](/tutorials/graphql-api#sign-users-in-with-mutations) |
| `commentAdded` | [用订阅推送新评论](/tutorials/graphql-api#push-new-comments-with-subscriptions) |

> info **提示** 完成后的应用位于 GitHub：[nestjs/example-graphql-api](https://github.com/nestjs/example-graphql-api)，其中包含测试和 CI 工作流。

你需要 Node.js 22.18 或更高版本（它直接运行订阅脚本中的 TypeScript，并内置 WebSocket 客户端），以及用于在本地运行 PostgreSQL 的 Docker。

#### 创建项目

使用 [Nest CLI](/cli/overview) 创建项目。`--minimal` 会生成一个代码集中在单个文件中的应用，本教程会替换该文件。它还会安装 [NestJS Observe SDK](/observability/sdk)，即 `@nestjs/observe`，并将其接入该文件；应用自身的文件会保留它：

```bash
$ npm i -g @nestjs/cli
$ nest new blog-api --minimal
$ cd blog-api
```

安装 [Node 适配器](/http/performance#node-adapter) 以替代 Express，以及 GraphQL 各包、DataLoader、class-validator，还有用于配置、数据库、登录和限流的包：

```bash
$ npm uninstall @nestjs/platform-express @types/express
$ npm i --save @nestjs/platform-node @nestjs/graphql @nestjs/apollo @apollo/server @as-integrations/express5 graphql graphql-ws graphql-subscriptions dataloader class-validator class-transformer zod @nestjs/config @nestjs/drizzle drizzle-orm@rc pg @nestjs/authentication @nestjs/throttler
$ npm i --save-dev drizzle-kit@rc @types/pg @nestjs/testing vitest vite
```

Apollo 驱动同样通过 Apollo Server 的 Express 集成在 Node 适配器上提供 GraphQL，而该适配器的请求和响应具有 Express API：如果没有 `@as-integrations/express5`，应用会在启动时以 `The "@as-integrations/express5" package is missing` 停止。`@nestjs/graphql` 已依赖 `graphql-ws`；测试和一个脚本会导入它的客户端。

删除 `src/main.ts`：[组装应用](/tutorials/graphql-api#assemble-the-application) 会写入一个新文件。在容器中启动 PostgreSQL：

```bash
$ docker run -d --name blog-db -e POSTGRES_PASSWORD=blog -e POSTGRES_DB=blog -p 5432:5432 postgres:17
```

在项目根目录创建 `.env` 文件，`ConfigModule` 和 `drizzle-kit` 会读取它：

```bash
DATABASE_URL=postgres://postgres:blog@localhost:5432/blog
# 用以下命令生成：openssl rand -base64 32
JWT_SECRET=
```

配置是一个 Zod schema，由 `ConfigModule` 在启动时校验，与[其他教程](/tutorials/rest-api-jwt-authentication#store-notes-in-postgresql) 一样。当某个变量缺失或格式错误时，应用会拒绝启动：

```typescript
@@filename(src/config)
import { z } from 'zod';

export const envSchema = z.object({
  NODE_ENV: z.enum(['development', 'test', 'production']).default('development'),
  PORT: z.coerce.number().int().default(3000),
  DATABASE_URL: z.url(),
  // 为访问令牌签名：至少 32 字节。
  JWT_SECRET: z.string().min(32),
  // 允许调用该 API 的浏览器来源，以逗号分隔。默认为空。
  CORS_ORIGINS: z
    .string()
    .default('')
    .transform((value) => value.split(',').map((origin) => origin.trim()).filter(Boolean))
    .pipe(z.array(z.url())),
});

export type Env = z.infer<typeof envSchema>;
```

#### 把博客存入 PostgreSQL

以下是各张表，用 Drizzle 的 schema 语言描述。`refresh_tokens` 是 `@nestjs/authentication` 为刷新令牌保存的数据，与[教程 1](/tutorials/rest-api-jwt-authentication#store-the-refresh-tokens) 一样：

```typescript
@@filename(src/database/schema)
import { boolean, index, jsonb, pgTable, text, timestamp, uuid } from 'drizzle-orm/pg-core';

// 毫秒精度，与 JavaScript Date 一致：游标保存的值与它比较的值完全相同。
const at = (name: string) => timestamp(name, { withTimezone: true, mode: 'date', precision: 3 });

export const users = pgTable('users', {
  id: uuid('id').primaryKey().defaultRandom(),
  email: text('email').notNull().unique(),
  name: text('name').notNull(),
  passwordHash: text('password_hash').notNull(),
  createdAt: at('created_at').notNull().defaultNow(),
});

export const posts = pgTable(
  'posts',
  {
    id: uuid('id').primaryKey().defaultRandom(),
    authorId: uuid('author_id')
      .notNull()
      .references(() => users.id, { onDelete: 'cascade' }),
    title: text('title').notNull(),
    body: text('body').notNull(),
    // 文章为草稿时为 null。
    publishedAt: at('published_at'),
    createdAt: at('created_at').notNull().defaultNow(),
    updatedAt: at('updated_at').notNull().defaultNow(),
  },
  (table) => [
    // 已发布列表，最新在前，以 id 作为并列时的次序依据。
    index('posts_published_at_id_idx').on(table.publishedAt.desc(), table.id.desc()),
    index('posts_author_id_created_at_idx').on(table.authorId, table.createdAt),
  ],
);

export const comments = pgTable(
  'comments',
  {
    id: uuid('id').primaryKey().defaultRandom(),
    postId: uuid('post_id')
      .notNull()
      .references(() => posts.id, { onDelete: 'cascade' }),
    authorId: uuid('author_id')
      .notNull()
      .references(() => users.id, { onDelete: 'cascade' }),
    body: text('body').notNull(),
    createdAt: at('created_at').notNull().defaultNow(),
  },
  (table) => [index('comments_post_id_created_at_idx').on(table.postId, table.createdAt)],
);

// @nestjs/authentication 为刷新令牌保存的数据，按其 SHA-256 存储。
export const refreshTokens = pgTable(
  'refresh_tokens',
  {
    id: text('id').primaryKey(),
    familyId: text('family_id').notNull(),
    userId: text('user_id').notNull(),
    createdAt: at('created_at').notNull(),
    expiresAt: at('expires_at').notNull(),
    familyExpiresAt: at('family_expires_at').notNull(),
    usedAt: at('used_at'),
    // 令牌族中任一令牌被撤销时，整个族即被撤销。
    revoked: boolean('revoked').notNull().default(false),
    claims: jsonb('claims').$type<Record<string, unknown>>(),
  },
  (table) => [
    index('refresh_tokens_family_id_idx').on(table.familyId),
    index('refresh_tokens_user_id_idx').on(table.userId),
    index('refresh_tokens_family_expires_at_idx').on(table.familyExpiresAt),
  ],
);

export type UserRow = typeof users.$inferSelect;
export type PostRow = typeof posts.$inferSelect;
export type CommentRow = typeof comments.$inferSelect;
```

草稿就是没有 `publishedAt` 的文章。PostgreSQL 默认保存微秒，而 JavaScript 的 `Date` 是毫秒，因此时间戳的精度设为 3：这样游标保存的值与它比较的值完全一致。在项目根目录添加 `drizzle.config.ts`：

```typescript
@@filename(drizzle.config)
import { defineConfig } from 'drizzle-kit';

export default defineConfig({
  dialect: 'postgresql',
  schema: './src/database/schema.ts',
  out: './drizzle',
  dbCredentials: {
    url: process.env.DATABASE_URL!,
  },
});
```

根据 schema 生成第一个迁移并应用（参见[迁移](/data/drizzle#migrations)）：

```bash
$ npx drizzle-kit generate --name=init
$ npx drizzle-kit migrate
```

#### 用 TypeScript 定义 schema

在代码优先方式中，Nest 从类及其装饰器生成 GraphQL schema（参见[对象类型](/graphql/resolvers#object-types)）。一个用户：

```typescript
@@filename(src/users/user.model)
import { Field, ID, ObjectType } from '@nestjs/graphql';

@ObjectType()
export class User {
  @Field(() => ID)
  id: string;

  @Field()
  name: string;

  // 不是 @Field：UsersResolver 会把它加入 schema，且只对用户本人提供。
  email: string;

  @Field()
  createdAt: Date;
}
```

`email` 是一个属性，但不是字段：只有检查了请求者是谁的字段解析器才会[把它放进 schema](/tutorials/graphql-api#batch-nested-fields-with-dataloader)。下面是一个文章类型，以及文章列表所在的连接（connection），即 Relay 和大多数客户端用于分页的结构：

```typescript
@@filename(src/posts/post.model)
import { Field, ID, ObjectType } from '@nestjs/graphql';

@ObjectType()
export class Post {
  @Field(() => ID)
  id: string;

  @Field()
  title: string;

  @Field()
  body: string;

  @Field(() => Date, { nullable: true, description: 'Null while the post is a draft.' })
  publishedAt: Date | null;

  @Field()
  createdAt: Date;

  @Field()
  updatedAt: Date;

  // 由 PostsResolver 解析为 `author`。
  authorId: string;
}

@ObjectType()
export class PostEdge {
  @Field()
  cursor: string;

  @Field(() => Post)
  node: Post;
}

@ObjectType()
export class PageInfo {
  @Field()
  hasNextPage: boolean;

  @Field(() => String, { nullable: true })
  endCursor: string | null;
}

@ObjectType()
export class PostConnection {
  @Field(() => [PostEdge])
  edges: PostEdge[];

  @Field(() => PageInfo)
  pageInfo: PageInfo;
}
```

一个评论类型：

```typescript
@@filename(src/posts/comment.model)
import { Field, ID, ObjectType } from '@nestjs/graphql';

@ObjectType()
export class Comment {
  @Field(() => ID)
  id: string;

  @Field()
  body: string;

  @Field()
  createdAt: Date;

  postId: string;
  // 由 CommentsResolver 解析为 `author`。
  authorId: string;
}
```

文章的 author 和 comments 并不是这些类的属性：它们是各自带解析器的字段，由解析器批量加载它们。

##### 用 class-validator 校验参数

参数是带 class-validator 规则的 `@ArgsType()` 和 `@InputType()` 类，由全局 `ValidationPipe` 在解析器运行之前校验（参见[校验](/application/validation)）。同一个类既定义 GraphQL 类型又定义规则，因此两者不会彼此偏离。类型错误的值由 GraphQL 拒绝；其余由规则检查，例如 UUID 的格式或标题的长度：

```typescript
@@filename(src/posts/posts.inputs)
import { ArgsType, Field, ID, InputType, Int } from '@nestjs/graphql';
import { IsOptional, IsString, IsUUID, Length, Max, MaxLength, Min, ValidateIf } from 'class-validator';

// 可选，但绝不为 null：@IsOptional() 会让 null 通过，进入 NOT NULL 列。
const ifSent = ValidateIf((_object, value) => value !== undefined);

@ArgsType()
export class PostArgs {
  @Field(() => ID)
  @IsUUID()
  id: string;
}

/** 列表的大小，例如一篇文章的评论。 */
@ArgsType()
export class FirstArgs {
  @Field(() => Int, { defaultValue: 10 })
  @Min(1)
  @Max(50)
  first: number;
}

@ArgsType()
export class PostsArgs extends FirstArgs {
  @Field(() => String, { nullable: true, description: 'The endCursor of the previous page.' })
  @IsOptional()
  @MaxLength(100)
  after?: string | null;
}

@InputType()
export class CreatePostInput {
  @Field()
  @Length(1, 200)
  title: string;

  @Field()
  @MaxLength(50_000)
  body: string;
}

@InputType()
export class UpdatePostInput {
  @Field(() => ID)
  @IsUUID()
  id: string;

  @Field(() => String, { nullable: true })
  @ifSent
  @IsString()
  @Length(1, 200)
  title?: string;

  @Field(() => String, { nullable: true })
  @ifSent
  @IsString()
  @MaxLength(50_000)
  body?: string;
}

@InputType()
export class AddCommentInput {
  @Field(() => ID)
  @IsUUID()
  postId: string;

  @Field()
  @Length(1, 5_000)
  body: string;
}

@ArgsType()
export class CommentAddedArgs {
  @Field(() => ID)
  @IsUUID()
  postId: string;
}
```

- **可选，但绝不为 null。** 客户端可以为任何可为 null 的参数发送 `null`。`@IsOptional()` 对 `null` 也会跳过规则，因此 `title: null` 会进入 `NOT NULL` 列并在那里失败，表现为内部错误。`ifSent` 只在字段缺失时才跳过规则。
- **每个列表都有上限**，并且 id 必须是 UUID：其他任何字符串都会被 PostgreSQL 以自己的错误拒绝。

#### 读写文章

每个读取文章的查询都会加上同一个条件，因此草稿是否可见只在一个地方决定：

```typescript
@@filename(src/posts/visibility)
import { eq, isNotNull, or, type SQL } from 'drizzle-orm';
import { posts } from '../database/schema.js';

/** 查看者可以看到的文章：所有已发布文章，以及查看者自己的草稿。每个读取文章的查询都会用它。 */
export function visibleTo(viewerId: string | null): SQL {
  const published = isNotNull(posts.publishedAt);
  return viewerId ? or(published, eq(posts.authorId, viewerId))! : published;
}
```

Nest 的 GraphQL 驱动会把 `HttpException` 转换为带代码的错误：400 变为 `BAD_REQUEST`，401 变为 `UNAUTHENTICATED`，403 变为 `FORBIDDEN`，422 变为 `BAD_USER_INPUT`，其他所有状态码（包括 404 和 409）都变为 `INTERNAL_SERVER_ERROR`，而它对客户端毫无帮助。其余的应答是自带代码的 `GraphQLError`：

```typescript
@@filename(src/graphql/errors)
import { Catch, type ValidationError } from '@nestjs/common';
import type { GqlExceptionFilter } from '@nestjs/graphql';
import { GraphQLError } from 'graphql';

export function notFound(what: string): never {
  throw new GraphQLError(`${what} not found`, { extensions: { code: 'NOT_FOUND' } });
}

/** 校验管道的错误：BAD_USER_INPUT，按字段带上每条消息。 */
export function badUserInput(errors: ValidationError[]): GraphQLError {
  const fields = Object.fromEntries(errors.map((error) => [error.property, Object.values(error.constraints ?? {})]));
  return new GraphQLError(Object.values(fields).flat().join('; '), {
    extensions: { code: 'BAD_USER_INPUT', fields },
  });
}

/** GraphQLError 是代码主动选择的应答：直接传递即可。否则 Nest 会把它记录为意外错误。 */
@Catch(GraphQLError)
export class GraphQLErrorFilter implements GqlExceptionFilter {
  catch(error: GraphQLError) {
    return error;
  }
}
```

- **`badUserInput()`** 取代 `ValidationPipe` 的默认异常（400，驱动会将其报告为 `BAD_REQUEST`），改用 `extensions.originalError` 中的消息。
- **`GraphQLErrorFilter`** 是一个[异常过滤器](/graphql/other-features#exception-filters)。Nest 会把所有不是 `HttpException` 的错误连同堆栈记录为意外错误：没有这个过滤器，每个 `NOT_FOUND` 都会成为其中之一。

服务负责读写文章和评论：

```typescript
@@filename(src/posts/posts.service)
import { ForbiddenException, Inject, Injectable } from '@nestjs/common';
import { InjectDrizzle } from '@nestjs/drizzle';
import { isUUID } from 'class-validator';
import { and, desc, eq, isNotNull, lt, or, sql } from 'drizzle-orm';
import type { NodePgDatabase } from 'drizzle-orm/node-postgres';
import { GraphQLError } from 'graphql';
import { PubSub } from 'graphql-subscriptions';
import { comments, posts, type CommentRow, type PostRow } from '../database/schema.js';
import { notFound } from '../graphql/errors.js';
import type { AddCommentInput, CreatePostInput, PostsArgs, UpdatePostInput } from './posts.inputs.js';
import { visibleTo } from './visibility.js';

export const PUB_SUB = Symbol('PUB_SUB');
// 每篇文章一个主题：一条评论只唤醒它所属文章的订阅者。
export const commentAddedTopic = (postId: string) => `commentAdded.${postId}`;

@Injectable()
export class PostsService {
  constructor(
    @InjectDrizzle() private readonly db: NodePgDatabase,
    @Inject(PUB_SUB) private readonly pubSub: PubSub,
  ) {}

  /** 已发布文章，最新在前，一次一页。 */
  async list({ first, after }: PostsArgs) {
    const cursor = after ? decodeCursor(after) : undefined;
    const rows = await this.db
      .select()
      .from(posts)
      .where(
        and(
          isNotNull(posts.publishedAt),
          // 位于游标之后：发布更早，或处于同一毫秒但 id 更小。
          cursor &&
            or(
              lt(posts.publishedAt, cursor.publishedAt),
              and(eq(posts.publishedAt, cursor.publishedAt), lt(posts.id, cursor.id)),
            ),
        ),
      )
      .orderBy(desc(posts.publishedAt), desc(posts.id))
      // 多取一条：如果它返回了，就说明还有下一页。
      .limit(first + 1);
    const edges = rows.slice(0, first).map((node) => ({ node, cursor: encodeCursor(node) }));
    return { edges, pageInfo: { hasNextPage: rows.length > first, endCursor: edges.at(-1)?.cursor ?? null } };
  }

  /** 查看者可以看到时的文章：别人的草稿与不存在的 id 一样视为缺失。 */
  async findVisible(id: string, viewerId: string | null): Promise<PostRow | null> {
    const [post] = await this.db
      .select()
      .from(posts)
      .where(and(eq(posts.id, id), visibleTo(viewerId)));
    return post ?? null;
  }

  async create(authorId: string, input: CreatePostInput): Promise<PostRow> {
    const [post] = await this.db
      .insert(posts)
      .values({ ...input, authorId })
      .returning();
    return post;
  }

  async update(authorId: string, { id, ...changes }: UpdatePostInput): Promise<PostRow> {
    // 作者是语句的一部分：检查与写入之间没有时间窗口。
    const [post] = await this.db
      .update(posts)
      .set({ ...changes, updatedAt: new Date() })
      .where(and(eq(posts.id, id), eq(posts.authorId, authorId)))
      .returning();
    return post ?? this.refuse(id, authorId);
  }

  async publish(authorId: string, id: string): Promise<PostRow> {
    // coalesce()：再次发布已发布的文章会保留其日期。
    const [post] = await this.db
      .update(posts)
      .set({ publishedAt: sql`coalesce(${posts.publishedAt}, now())` })
      .where(and(eq(posts.id, id), eq(posts.authorId, authorId)))
      .returning();
    return post ?? this.refuse(id, authorId);
  }

  async addComment(authorId: string, { postId, body }: AddCommentInput): Promise<CommentRow> {
    // 仅限已发布文章：对任何人（包括作者）来说，草稿都不接受评论。
    if (!(await this.findVisible(postId, null))) {
      notFound('Post');
    }
    const [comment] = await this.db.insert(comments).values({ postId, authorId, body }).returning();
    await this.pubSub.publish(commentAddedTopic(postId), { commentAdded: comment });
    return comment;
  }

  /** 写入没有匹配到任何内容的原因：如果用户能看到别人的文章，则为 FORBIDDEN。 */
  private async refuse(id: string, userId: string): Promise<never> {
    if (await this.findVisible(id, userId)) {
      throw new ForbiddenException('Only the author can change this post');
    }
    notFound('Post');
  }
}

// 游标是最后一篇文章的发布时间和 id：对客户端不透明，
// 但同样是客户端输入，在进入查询之前会被检查。
function encodeCursor(post: PostRow): string {
  return Buffer.from(`${post.publishedAt!.getTime()}:${post.id}`).toString('base64url');
}

function decodeCursor(cursor: string): { publishedAt: Date; id: string } {
  const [, time, id] = /^(\d{1,15}):([0-9a-f-]{36})$/.exec(Buffer.from(cursor, 'base64url').toString()) ?? [];
  if (!time || !isUUID(id)) {
    throw new GraphQLError('Invalid cursor', { extensions: { code: 'BAD_USER_INPUT' } });
  }
  return { publishedAt: new Date(Number(time)), id };
}
```

- **列表用游标分页**：取最后一篇文章的发布时间和 id，并让 id 在排序、索引和条件中作为并列时的次序依据。与偏移量不同，有人在读第 1 页时发布了新文章，游标不会错位。但它同样是客户端输入，在进入查询之前会被检查。
- **写入是一条语句，作者条件放在 `WHERE` 子句中。** 当它没有匹配到任何内容时，`refuse()` 会查明原因：用户能看到但属于别人的文章是 `FORBIDDEN`。其余情况（包括别人的草稿）都是 `NOT_FOUND`，与不存在的 id 相同。

解析器把 `Post` 的查询、变更和字段映射到服务（参见[解析器](/graphql/resolvers) 和[变更](/graphql/mutations)）：

```typescript
@@filename(src/posts/posts.resolver)
import { Authenticate, CurrentUser } from '@nestjs/authentication';
import { Args, Mutation, Parent, Query, ResolveField, Resolver } from '@nestjs/graphql';
import { User } from '../users/user.model.js';
import { UsersLoader } from '../users/users.loader.js';
import { CommentsLoader } from './comments.loader.js';
import { Comment } from './comment.model.js';
import { Post, PostConnection } from './post.model.js';
import { CreatePostInput, FirstArgs, PostArgs, PostsArgs, UpdatePostInput } from './posts.inputs.js';
import { PostsService } from './posts.service.js';

// 任何人都可以读取；已登录的查看者还能看到自己的草稿。
@Authenticate({ optional: true })
@Resolver(() => Post)
export class PostsResolver {
  constructor(
    private readonly postsService: PostsService,
    private readonly usersLoader: UsersLoader,
    private readonly commentsLoader: CommentsLoader,
  ) {}

  @Query(() => PostConnection)
  posts(@Args() args: PostsArgs) {
    return this.postsService.list(args);
  }

  @Query(() => Post, { nullable: true })
  post(@Args() { id }: PostArgs, @CurrentUser('id') viewerId: string | null) {
    return this.postsService.findVisible(id, viewerId ?? null);
  }

  @ResolveField(() => User)
  author(@Parent() post: Post) {
    return this.usersLoader.load(post.authorId);
  }

  @ResolveField(() => [Comment])
  comments(@Parent() post: Post, @Args() { first }: FirstArgs) {
    return this.commentsLoader.load(post.id, first);
  }

  @Authenticate({ optional: false })
  @Mutation(() => Post)
  createPost(@CurrentUser('id') userId: string, @Args('input') input: CreatePostInput) {
    return this.postsService.create(userId, input);
  }

  @Authenticate({ optional: false })
  @Mutation(() => Post)
  updatePost(@CurrentUser('id') userId: string, @Args('input') input: UpdatePostInput) {
    return this.postsService.update(userId, input);
  }

  @Authenticate({ optional: false })
  @Mutation(() => Post)
  publishPost(@CurrentUser('id') userId: string, @Args() { id }: PostArgs) {
    return this.postsService.publish(userId, id);
  }
}
```

- **读取对所有人开放。** `@nestjs/authentication` 的全局守卫要求每个操作都有用户，除非另行声明。使用 `optional` 时，匿名读者可以通行；而当请求带有有效令牌时，`@CurrentUser()` 仍能得到该用户，因此作者能看到自己的草稿。`@Public()` 操作不执行认证，其中的 `@CurrentUser()` 始终为 `null`。
- **变更再次要求用户**，把 `optional` 设为 `false`：方法上的选项会合并覆盖类上的选项。
- **`author` 和 `comments` 经由 `UsersLoader` 和 `CommentsLoader`**，这两个类由下一节编写。

#### 用 DataLoader 批量加载嵌套字段

一个请求查询 50 篇文章及其作者时，`author` 解析器会运行 50 次；如果每次解析器都自己发一条查询，这个请求就会发出 51 条：这就是 N+1 问题。[DataLoader](https://github.com/graphql/dataloader) 是 GraphQL 项目提供的一个小库（本文档其他部分未涉及），它把解析器在一个 tick 内请求的键收集起来，再用一次批量函数调用加载它们。每张表都有自己的加载器，放在相应功能目录中：新增字段时，给该字段所读表的加载器添加方法，而不是给某个共享类添加。按 id 查询用户：

```typescript
@@filename(src/users/users.loader)
import { Injectable, Scope } from '@nestjs/common';
import { InjectDrizzle } from '@nestjs/drizzle';
import DataLoader from 'dataloader';
import { getColumns, inArray } from 'drizzle-orm';
import type { NodePgDatabase } from 'drizzle-orm/node-postgres';
import { users } from '../database/schema.js';
import type { User } from './user.model.js';

const { passwordHash: _, ...columns } = getColumns(users);

/** 按 id 查询用户，仅供一次请求使用。 */
@Injectable({ scope: Scope.REQUEST })
export class UsersLoader {
  // 批处理但不用缓存：订阅在运行期间就是一个请求，
  // 它的每个事件都必须看到当前的行。
  private readonly byId = new DataLoader<string, User | undefined>(
    async (ids) => {
      const rows = await this.db.select(columns).from(users).where(inArray(users.id, [...ids]));
      return ids.map((id) => rows.find((row) => row.id === id));
    },
    { cache: false },
  );

  constructor(@InjectDrizzle() private readonly db: NodePgDatabase) {}

  load(id: string): Promise<User | undefined> {
    return this.byId.load(id);
  }
}
```

- **请求作用域。** Nest 会为每个请求创建新实例（参见[注入作用域](/fundamentals/provider-scopes)），因此一个请求的批量数据永远不会与另一个查看者的混在一起，它加载的数据也不会比请求活得更久。作用域会向上冒泡：注入加载器的解析器同样成为请求作用域。在 GraphQL 中，一个请求就是一个操作；而订阅在运行期间算作一个请求，无论它的套接字还承载了什么。
- **不用缓存。** 如果开启 DataLoader 的缓存，订阅后续的事件拿到的会是它第一个事件加载的行：作者发布文章之后到达的评论，仍会把作者的文章列成它们当初的样子。

每篇文章的首批评论：`row_number()` 会为每篇文章的评论单独编号，而 `LIMIT` 会把它们全部一起计数；每个 `first` 都有自己的 DataLoader，因为它会改变查询：

```typescript
@@filename(src/posts/comments.loader)
import { Injectable, Scope } from '@nestjs/common';
import { InjectDrizzle } from '@nestjs/drizzle';
import DataLoader from 'dataloader';
import { getColumns, inArray, lte, sql } from 'drizzle-orm';
import type { NodePgDatabase } from 'drizzle-orm/node-postgres';
import { comments, type CommentRow } from '../database/schema.js';

/** 每篇文章的首批评论，最早在前，仅供一次请求使用。 */
@Injectable({ scope: Scope.REQUEST })
export class CommentsLoader {
  // 每个 `first` 一个 DataLoader。
  private readonly byFirst = new Map<number, DataLoader<string, CommentRow[]>>();

  constructor(@InjectDrizzle() private readonly db: NodePgDatabase) {}

  load(postId: string, first: number): Promise<CommentRow[]> {
    let loader = this.byFirst.get(first);
    if (!loader) {
      // 不用缓存，与 UsersLoader 相同。
      loader = new DataLoader((postIds) => this.firstOfEach([...postIds], first), { cache: false });
      this.byFirst.set(first, loader);
    }
    return loader.load(postId);
  }

  private async firstOfEach(postIds: string[], first: number): Promise<CommentRow[][]> {
    const ranked = this.db
      .select({
        ...getColumns(comments),
        rank: sql<number>`row_number() over (partition by ${comments.postId} order by ${comments.createdAt}, ${comments.id})`.as('rank'),
      })
      .from(comments)
      .where(inArray(comments.postId, postIds))
      .as('ranked');
    const rows = await this.db.select().from(ranked).where(lte(ranked.rank, first)).orderBy(ranked.rank);
    return postIds.map((id) => rows.filter((row) => row.postId === id));
  }
}
```

每位作者最新的、查看者可以看到的文章。一次请求只有一个查看者，因此键中不含它；若用单例，就会一直保留它见到的第一个查看者：

```typescript
@@filename(src/posts/posts.loader)
import { Injectable, Scope } from '@nestjs/common';
import { InjectDrizzle } from '@nestjs/drizzle';
import DataLoader from 'dataloader';
import { and, getColumns, inArray, lte, sql } from 'drizzle-orm';
import type { NodePgDatabase } from 'drizzle-orm/node-postgres';
import { posts, type PostRow } from '../database/schema.js';
import { visibleTo } from './visibility.js';

/** 每位作者最新的、查看者可以看到的文章，仅供一次请求使用。 */
@Injectable({ scope: Scope.REQUEST })
export class PostsLoader {
  // 每个 `first` 一个 DataLoader；一次请求只有一个查看者。
  private readonly byFirst = new Map<number, DataLoader<string, PostRow[]>>();

  constructor(@InjectDrizzle() private readonly db: NodePgDatabase) {}

  load(authorId: string, first: number, viewerId: string | null): Promise<PostRow[]> {
    let loader = this.byFirst.get(first);
    if (!loader) {
      // 不用缓存，与 UsersLoader 相同。
      loader = new DataLoader((authorIds) => this.latestOfEach([...authorIds], first, viewerId), { cache: false });
      this.byFirst.set(first, loader);
    }
    return loader.load(authorId);
  }

  private async latestOfEach(authorIds: string[], first: number, viewerId: string | null): Promise<PostRow[][]> {
    const ranked = this.db
      .select({
        ...getColumns(posts),
        rank: sql<number>`row_number() over (partition by ${posts.authorId} order by ${posts.publishedAt} desc nulls first, ${posts.id} desc)`.as('rank'),
      })
      .from(posts)
      .where(and(inArray(posts.authorId, authorIds), visibleTo(viewerId)))
      .as('ranked');
    const rows = await this.db.select().from(ranked).where(lte(ranked.rank, first)).orderBy(ranked.rank);
    return authorIds.map((id) => rows.filter((row) => row.authorId === id));
  }
}
```

`User.posts` 读取文章，因此它的解析器放在 posts 目录下：`PostsModule` 为 `UsersLoader` 导入 `UsersModule`，反向则从不发生，因此两个模块不会互相导入：

```typescript
@@filename(src/posts/user-posts.resolver)
import { Authenticate, CurrentUser } from '@nestjs/authentication';
import { Args, Parent, ResolveField, Resolver } from '@nestjs/graphql';
import { User } from '../users/user.model.js';
import { Post } from './post.model.js';
import { FirstArgs } from './posts.inputs.js';
import { PostsLoader } from './posts.loader.js';

// User 的一个字段，在 posts 功能中解析：PostsModule 导入 UsersModule，绝不反向。
@Authenticate({ optional: true })
@Resolver(() => User)
export class UserPostsResolver {
  constructor(private readonly postsLoader: PostsLoader) {}

  @ResolveField(() => [Post])
  posts(@Parent() user: User, @Args() { first }: FirstArgs, @CurrentUser('id') viewerId: string | null) {
    return this.postsLoader.load(user.id, first, viewerId ?? null);
  }
}
```

用户解析器提供 `me` 和 `email`：

```typescript
@@filename(src/users/users.resolver)
import { Authenticate, CurrentUser } from '@nestjs/authentication';
import { Parent, Query, ResolveField, Resolver } from '@nestjs/graphql';
import { User } from './user.model.js';

@Authenticate({ optional: true })
@Resolver(() => User)
export class UsersResolver {
  @Authenticate({ optional: false })
  @Query(() => User)
  me(@CurrentUser() user: User) {
    return user;
  }

  // 只有用户本人能看到自己的地址；其他人都得到 null。
  @ResolveField(() => String, { nullable: true })
  email(@Parent() user: User, @CurrentUser('id') viewerId: string | null) {
    return user.id === viewerId ? user.email : null;
  }
}
```

`email` 是字段解析器，而不是[字段中间件](/graphql/field-middleware)：中间件只有上下文，而在 `graphql-ws` 上，上下文的 `req.user` 是套接字上最后一次通过认证的操作的用户（参见 [GraphQL 与 WebSocket](/security/authentication#graphql-and-websockets)），而 `@CurrentUser()` 取的是当前操作的用户。

#### 用变更让用户登录

注册、登录和刷新与[教程 1](/tutorials/rest-api-jwt-authentication#sign-users-in-with-jwts) 相同：访问令牌有效 15 分钟，刷新令牌每次使用都轮换。这里它们都是变更，并且有三个文件与教程 1 不同：用户有名字、用户类型就是 GraphQL 模型、realm（域）是博客自己的。用户仓库是唯一能看到密码哈希的代码：

```typescript
@@filename(src/users/users.repository)
import { Injectable } from '@nestjs/common';
import { InjectDrizzle } from '@nestjs/drizzle';
import { eq } from 'drizzle-orm';
import type { NodePgDatabase } from 'drizzle-orm/node-postgres';
import { users } from '../database/schema.js';
import type { User } from './user.model.js';

const columns = { id: users.id, email: users.email, name: users.name, createdAt: users.createdAt };

/** 只有 `User` 对象会离开这个类：密码哈希留在内部。 */
@Injectable()
export class UsersRepository {
  constructor(@InjectDrizzle() private readonly db: NodePgDatabase) {}

  /** 新用户；邮箱已被占用时为 `null`。 */
  async create(email: string, name: string, passwordHash: string): Promise<User | null> {
    // 一条语句：同一邮箱的两次注册不可能都成功。
    const [user] = await this.db
      .insert(users)
      .values({ email: normalize(email), name, passwordHash })
      .onConflictDoNothing({ target: users.email })
      .returning(columns);
    return user ?? null;
  }

  async findById(id: string): Promise<User | null> {
    const [user] = await this.db.select(columns).from(users).where(eq(users.id, id));
    return user ?? null;
  }

  /** 仅用于密码登录。 */
  async findCredentials(email: string): Promise<{ user: User; passwordHash: string } | null> {
    const [row] = await this.db.select().from(users).where(eq(users.email, normalize(email)));
    if (!row) {
      return null;
    }
    const { passwordHash, ...user } = row;
    return { user, passwordHash };
  }
}

export const normalize = (email: string) => email.trim().normalize('NFC').toLowerCase();
```

用户模块把它提供给认证代码，并把 `UsersLoader` 提供给 posts 功能：

```typescript
@@filename(src/users/users.module)
import { Module } from '@nestjs/common';
import { UsersLoader } from './users.loader.js';
import { UsersRepository } from './users.repository.js';
import { UsersResolver } from './users.resolver.js';

@Module({
  providers: [UsersRepository, UsersLoader, UsersResolver],
  exports: [UsersRepository, UsersLoader],
})
export class UsersModule {}
```

`PasswordHasher` 使用 scrypt 哈希密码。当账号不存在时，`verify()` 会校验一个虚拟哈希，因此响应时间不会泄露哪些邮箱已经注册：

```typescript
@@filename(src/auth/credentials.service)
import { Injectable } from '@nestjs/common';
import { PasswordHasher } from '@nestjs/authentication';
import { GraphQLError } from 'graphql';
import type { User } from '../users/user.model.js';
import { UsersRepository } from '../users/users.repository.js';

@Injectable()
export class CredentialsService {
  constructor(
    private readonly usersRepository: UsersRepository,
    private readonly passwordHasher: PasswordHasher,
  ) {}

  async register(email: string, name: string, password: string): Promise<User> {
    const user = await this.usersRepository.create(email, name, await this.passwordHasher.hash(password));
    if (!user) {
      throw new GraphQLError('Email already registered', { extensions: { code: 'EMAIL_TAKEN' } });
    }
    return user;
  }

  /** 该用户；邮箱或密码错误时为 `null`。 */
  async verify(email: string, password: string): Promise<User | null> {
    const found = await this.usersRepository.findCredentials(email);
    // 账号不存在时，verify() 会校验一个虚拟哈希，因此响应
    // 时间不会泄露哪些邮箱已经注册。
    const valid = await this.passwordHasher.verify(password, found?.passwordHash);
    return valid && found ? found.user : null;
  }
}
```

`JwtBearerProvider` 读取 `Authorization` 请求头，校验令牌的签名、有效期、签发者和受众，并把它的声明（claims）传给 `validate()`：

```typescript
@@filename(src/auth/jwt-auth.provider)
import { Injectable } from '@nestjs/common';
import { AuthenticationRegistry, JwtBearerProvider, type JwtClaims } from '@nestjs/authentication';
import type { User } from '../users/user.model.js';
import { UsersRepository } from '../users/users.repository.js';

@Injectable()
export class JwtAuth extends JwtBearerProvider<User> {
  constructor(
    private readonly usersRepository: UsersRepository,
    registry: AuthenticationRegistry,
  ) {
    // 密钥、签发者和受众来自 `accessToken` 选项。
    super({ realm: 'blog' });
    registry.registerProvider(this);
  }

  // 在签名以及 `exp`、`iss`、`aud` 都校验通过后调用。
  // 返回 null（用户已被删除）即拒绝该令牌。
  validate({ sub }: JwtClaims) {
    return sub ? this.usersRepository.findById(sub) : null;
  }
}
```

有两个文件来自教程 1。原样复制 `src/auth/drizzle-refresh-token.store.ts`，取自[存储刷新令牌](/tutorials/rest-api-jwt-authentication#store-the-refresh-tokens)：它把刷新令牌保存在 PostgreSQL 中，其带条件的 `UPDATE` 让同一个令牌的两次刷新中恰好只有一次成功。复制 `src/auth/auth-types.ts`，取自[用户](/tutorials/rest-api-jwt-authentication#users)，但把 `User` 从 `../users/user.model.js` 导入（而非 `../users/user.js`），这样 `@CurrentUser('id')` 只接受 `User` 的键。

变更的输入，以及它们的返回值：

```typescript
@@filename(src/auth/auth.inputs)
import { Field, InputType, Int, ObjectType } from '@nestjs/graphql';
import { IsEmail, IsNotEmpty, Length, MaxLength } from 'class-validator';

@InputType()
export class SignUpInput {
  @Field()
  @IsEmail()
  email: string;

  @Field()
  @Length(1, 100)
  name: string;

  @Field()
  @Length(12, 128)
  password: string;
}

@InputType()
export class SignInInput {
  @Field()
  @IsEmail()
  email: string;

  // 这里不设最小长度：按旧规则设置的密码仍可登录。
  @Field()
  @MaxLength(128)
  password: string;
}

@InputType()
export class RefreshTokenInput {
  @Field()
  @IsNotEmpty()
  refreshToken: string;
}

@ObjectType()
export class AuthPayload {
  @Field()
  accessToken: string;

  @Field()
  refreshToken: string;

  @Field(() => Int, { description: "The access token's lifetime, in seconds." })
  expiresIn: number;
}
```

解析器用 `TokenService` 签发令牌。被重复使用的刷新令牌意味着有两方持有它，因此 `TokenService` 会撤销它的令牌族，并抛出 `AuthenticationError`，客户端收到的是 `UNAUTHENTICATED`（参见[向移动应用签发令牌](/security/authentication#issue-tokens-to-the-mobile-app)）：

```typescript
@@filename(src/auth/auth.resolver)
import { Logger, UnauthorizedException, UseGuards } from '@nestjs/common';
import { Public, TokenService } from '@nestjs/authentication';
import { Args, Mutation, Resolver } from '@nestjs/graphql';
import { SkipThrottle, Throttle, hours, minutes } from '@nestjs/throttler';
import { AuthPayload, RefreshTokenInput, SignInInput, SignUpInput } from './auth.inputs.js';
import { CredentialsService } from './credentials.service.js';
import { GqlThrottlerGuard } from './gql-throttler.guard.js';

@Public()
@UseGuards(GqlThrottlerGuard)
@Resolver()
export class AuthResolver {
  private readonly logger = new Logger(AuthResolver.name);

  constructor(
    private readonly credentialsService: CredentialsService,
    private readonly tokenService: TokenService,
  ) {}

  @SkipThrottle({ account: true })
  @Throttle({ default: { limit: 10, ttl: hours(1) } })
  @Mutation(() => AuthPayload)
  async signUp(@Args('input') { email, name, password }: SignUpInput) {
    const user = await this.credentialsService.register(email, name, password);
    return this.tokenService.issue(user.id, { method: 'password', claims: { amr: ['pwd'] } });
  }

  @Throttle({
    default: { limit: 30, ttl: minutes(15) },
    account: { limit: 5, ttl: minutes(15) },
  })
  @Mutation(() => AuthPayload)
  async signIn(@Args('input') { email, password }: SignInInput) {
    const user = await this.credentialsService.verify(email, password);
    if (!user) {
      this.logger.warn('Sign-in failed', { email });
      throw new UnauthorizedException('Invalid email or password');
    }
    return this.tokenService.issue(user.id, { method: 'password', claims: { amr: ['pwd'] } });
  }

  // 未知、已过期或已重复使用的刷新令牌为 UNAUTHENTICATED；重复使用会撤销整个令牌族。
  @Mutation(() => AuthPayload)
  refreshToken(@Args('input') { refreshToken }: RefreshTokenInput) {
    return this.tokenService.refresh(refreshToken);
  }
}
```

认证模块：

```typescript
@@filename(src/auth/auth.module)
import { Module } from '@nestjs/common';
import { UsersModule } from '../users/users.module.js';
import { AuthResolver } from './auth.resolver.js';
import { CredentialsService } from './credentials.service.js';
import { DrizzleRefreshTokenStore } from './drizzle-refresh-token.store.js';
import { JwtAuth } from './jwt-auth.provider.js';

@Module({
  imports: [UsersModule],
  providers: [AuthResolver, JwtAuth, CredentialsService, DrizzleRefreshTokenStore],
})
export class AuthModule {}
```

##### 对登录限流

限制与[教程 1](/tutorials/rest-api-jwt-authentication#rate-limit-sign-in) 相同。`src/auth/gql-throttler.guard.ts` 中的 `GqlThrottlerGuard` 是 [GraphQL](/security/rate-limiting#graphql) 一节中的守卫，只应用于 `AuthResolver`，因为启用 `fieldResolverEnhancers` 后，全局守卫会把每个被解析的字段都计数。它还重写了 `throwThrottlingException()`，改为抛出带 `TOO_MANY_REQUESTS` 代码和 `retryAfter` 的 `GraphQLError`；`retryAfter` 是距离解除封锁的秒数（`timeToBlockExpire`）：否则 429 会以 `INTERNAL_SERVER_ERROR` 到达客户端。本应用自己实现的是 `account` 追踪器，由 `AppModule` 配置，它从变更的参数（而不是请求体）中读取邮箱，并用用户仓库的 `normalize()` 规范化。同一个文件导出它：

```typescript
@@filename(src/auth/gql-throttler.guard)
// ...

/** 变更的 `input` 所指的地址，按用户表的存储方式规范化；没有则返回 `''`。 */
export function accountEmail(context: ExecutionContext): string {
  const email = GqlExecutionContext.create(context).getArgs<{ input?: { email?: unknown } }>().input?.email;
  return typeof email === 'string' ? normalize(email) : '';
}
```

#### 配置 GraphQL 模块

GraphQL 模块的选项来自一个类，由 Nest 连同它的依赖一起创建（参见[异步配置](/graphql/quick-start#async-configuration)）：

```typescript
@@filename(src/graphql/graphql.config)
import type { IncomingMessage } from 'node:http';
import type { ApolloDriverConfig } from '@nestjs/apollo';
import { Injectable } from '@nestjs/common';
import { WsAuthenticator } from '@nestjs/authentication';
import type { GqlOptionsFactory } from '@nestjs/graphql';
import { GraphQLError, getOperationAST, parse } from 'graphql';
import type { Context, SubscribePayload } from 'graphql-ws';
import type { Extra } from 'graphql-ws/use/ws';

type SocketContext = Context<Record<string, unknown> | undefined, Extra>;

@Injectable()
export class GraphqlConfig implements GqlOptionsFactory<ApolloDriverConfig> {
  constructor(private readonly wsAuthenticator: WsAuthenticator) {}

  createGqlOptions(): ApolloDriverConfig {
    const production = process.env.NODE_ENV === 'production';
    return {
      autoSchemaFile: true,
      sortSchema: true,
      subscriptions: {
        'graphql-ws': {
          onConnect: (context) => this.authenticateSocket(context as SocketContext),
          onSubscribe: (_context, _id, payload) => this.checkSocketOperation(payload),
        },
      },
      // 每个操作都会调用。在 graphql-ws 上，套接字的升级请求充当 `req`。
      context: ({ req, res, extra }: { req?: IncomingMessage; res?: unknown; extra?: Extra }) => ({
        req: req ?? extra?.request,
        res,
      }),
      fieldResolverEnhancers: ['guards', 'interceptors', 'filters'],
      formatError: (error) =>
        // 在生产环境中，不是有意抛出的错误不应向客户端透露任何信息。
        production && error.extensions?.code === 'INTERNAL_SERVER_ERROR'
          ? { message: 'Internal server error', path: error.path, extensions: { code: 'INTERNAL_SERVER_ERROR' } }
          : error,
    };
  }

  /** 每个套接字运行一次：返回 `false` 会以 4403 Forbidden 关闭它。 */
  private async authenticateSocket({ connectionParams, extra }: SocketContext) {
    // 浏览器无法在 WebSocket 上设置请求头：令牌通过 connectionParams 传入，
    // 再放到升级请求上，守卫会在每个操作中从那里读取它。
    if (typeof connectionParams?.authorization === 'string') {
      extra.request.headers.authorization = connectionParams.authorization;
    }
    const result = await this.wsAuthenticator.authenticateConnection(extra.socket, extra.request, { required: false });
    return result !== null;
  }

  /**
   * graphql-ws 在 Apollo Server 之外运行操作，Apollo Server 的插件不会作用于它们。
   * 套接字只提供订阅；查询和变更走 HTTP。
   */
  private checkSocketOperation({ query, operationName }: SubscribePayload) {
    let document;
    try {
      document = parse(query);
    } catch (error) {
      return [error as GraphQLError];
    }
    if (getOperationAST(document, operationName)?.operation !== 'subscription') {
      return [new GraphQLError('Only subscriptions are served over WebSocket: send queries and mutations over HTTP')];
    }
    return undefined;
  }
}
```

- **`context` 是一个函数**，这是 [GraphQL 与 WebSocket](/security/authentication#graphql-and-websockets) 的要求：守卫会读取上下文中 `req` 的请求头。
- **`fieldResolverEnhancers`** 让 Nest 在字段解析器上也运行守卫、拦截器和过滤器（参见[在字段解析器层执行增强器](/graphql/other-features#execute-enhancers-at-the-field-resolver-level)）。守卫为它们提供 `@CurrentUser()`。过滤器会记录它们抛出的内容：没有过滤器时，`Post.author` 中的错误会到达客户端，而日志里没有任何一行。
- **`formatError` 在生产环境中隐藏意外错误。** Apollo Server 在那里会省略堆栈，但保留消息，例如会带上主机名的数据库错误。
- **套接字在打开时认证一次。** 浏览器无法在 WebSocket 上设置请求头，因此客户端把令牌放在 `connectionParams` 中发送。`authenticateSocket()` 把它复制到升级请求上，并用 `WsAuthenticator` 校验，后者会运行守卫所用的各提供者。返回 `false` 会在任何操作之前以 4403 关闭套接字。
- **套接字只提供订阅。** `graphql-ws` 自己执行收到的内容，位于 Apollo Server 之外，因此 Apollo Server 的插件永远看不到它，而它执行查询或变更与执行订阅一样容易。自 `@nestjs/apollo` 14.2.2 起，Apollo 驱动会把 `introspection` 设置应用到套接字；在此之前，即使在生产环境中，内省查询也能通过套接字拿到 schema。`checkSocketOperation()` 除订阅外一律拒绝，因此发送查询或变更的唯一途径是 HTTP，并经过 Apollo Server 的检查。

#### 用订阅推送新评论

有两个解析器服务于评论：一个负责 `author` 字段，注入 `UsersLoader`；另一个负责 `addComment` 变更和 `commentAdded` 订阅（参见[订阅](/graphql/subscriptions)）。Nest 要求带 `@Subscription()` 的解析器是单例，因此它不能注入请求作用域的提供者：

```typescript
@@filename(src/posts/comments.resolver)
import { Inject } from '@nestjs/common';
import { Authenticate, CurrentUser } from '@nestjs/authentication';
import { Args, Mutation, Parent, ResolveField, Resolver, Subscription } from '@nestjs/graphql';
import { PubSub } from 'graphql-subscriptions';
import { notFound } from '../graphql/errors.js';
import { User } from '../users/user.model.js';
import { UsersLoader } from '../users/users.loader.js';
import { Comment } from './comment.model.js';
import { AddCommentInput, CommentAddedArgs } from './posts.inputs.js';
import { PostsService, PUB_SUB, commentAddedTopic } from './posts.service.js';

// 请求作用域，因为它注入了 UsersLoader。
@Authenticate({ optional: true })
@Resolver(() => Comment)
export class CommentAuthorResolver {
  constructor(private readonly usersLoader: UsersLoader) {}

  @ResolveField(() => User)
  author(@Parent() comment: Comment) {
    return this.usersLoader.load(comment.authorId);
  }
}

// 单例：对于带 @Subscription() 的解析器，Nest 要求如此。
@Resolver(() => Comment)
export class CommentsResolver {
  constructor(
    private readonly postsService: PostsService,
    @Inject(PUB_SUB) private readonly pubSub: PubSub,
  ) {}

  @Mutation(() => Comment)
  addComment(@CurrentUser('id') userId: string, @Args('input') input: AddCommentInput) {
    return this.postsService.addComment(userId, input);
  }

  @Subscription(() => Comment)
  async commentAdded(@Args() { postId }: CommentAddedArgs, @CurrentUser('id') userId: string) {
    // 订阅别人的草稿，与订阅一篇不存在的文章相同。
    if (!(await this.postsService.findVisible(postId, userId))) {
      notFound('Post');
    }
    // 每篇文章一个主题：一条评论只唤醒它所属文章的订阅者。
    return this.pubSub.asyncIterableIterator(commentAddedTopic(postId));
  }
}
```

- **按操作认证。** 守卫会针对该订阅运行，使用的令牌是套接字打开时的那个。
- **别人的草稿是 `NOT_FOUND`。** 草稿不接受评论，但其他任何应答都会告诉客户端该草稿存在。
- **每篇文章一个主题**，而不是一个主题加一个 [`filter`](/graphql/subscriptions#filtering-subscriptions)；后者会在每条评论到达时，对每篇文章的每个订阅者都运行一次。

posts 模块提供这四个解析器、服务、两个加载器和 `PubSub`：

```typescript
@@filename(src/posts/posts.module)
import { Module } from '@nestjs/common';
import { PubSub } from 'graphql-subscriptions';
import { UsersModule } from '../users/users.module.js';
import { CommentAuthorResolver, CommentsResolver } from './comments.resolver.js';
import { CommentsLoader } from './comments.loader.js';
import { PostsLoader } from './posts.loader.js';
import { PostsResolver } from './posts.resolver.js';
import { PostsService, PUB_SUB } from './posts.service.js';
import { UserPostsResolver } from './user-posts.resolver.js';

@Module({
  // 为了 UsersLoader。UsersModule 不导入 posts 功能的任何内容。
  imports: [UsersModule],
  providers: [
    PostsResolver,
    CommentsResolver,
    CommentAuthorResolver,
    UserPostsResolver,
    PostsService,
    PostsLoader,
    CommentsLoader,
    // 在本进程内存中：参见生产环境检查清单。
    { provide: PUB_SUB, useValue: new PubSub() },
  ],
  exports: [PostsLoader, CommentsLoader],
})
export class PostsModule {}
```

#### 组装应用

根模块注册配置、数据库、认证、GraphQL 和限流，以及应用于每个操作的管道和过滤器：

```typescript
@@filename(src/app.module)
import { ApolloDriver, type ApolloDriverConfig } from '@nestjs/apollo';
import { Module, ValidationPipe } from '@nestjs/common';
import { APP_FILTER, APP_PIPE } from '@nestjs/core';
import { AuthenticationModule } from '@nestjs/authentication';
import { ConfigModule, ConfigService } from '@nestjs/config';
import { DrizzleModule } from '@nestjs/drizzle';
import { GraphQLModule } from '@nestjs/graphql';
import { createObserveModule } from '@nestjs/observe';
import { ThrottlerModule, minutes, normalizeIp } from '@nestjs/throttler';
import { drizzle } from 'drizzle-orm/node-postgres';
import { AuthModule } from './auth/auth.module.js';
import { accountEmail } from './auth/gql-throttler.guard.js';
import { envSchema, type Env } from './config.js';
import { badUserInput, GraphQLErrorFilter } from './graphql/errors.js';
import { GraphqlConfig } from './graphql/graphql.config.js';
import { PostsModule } from './posts/posts.module.js';
import { UsersModule } from './users/users.module.js';

export const { ObserveModule, ObserveInstrument } = createObserveModule();

@Module({
  imports: [
    // 放在最前，因此最后关闭，仍能发送其他模块产生的数据。
    ObserveModule.forRoot({
      // 在 `npx @nestjs/observe link` 把密钥对写入 .env 之前为空：此时 SDK 不发送任何内容。
      appKey: process.env.OBSERVE_APP_KEY ?? '',
      appSecret: process.env.OBSERVE_APP_SECRET ?? '',
      serviceId: 'blog-api',
    }),
    ConfigModule.forRoot({ isGlobal: true, validationSchema: envSchema }),
    DrizzleModule.forRootAsync({
      inject: [ConfigService],
      useFactory: (config: ConfigService<Env, true>) => ({
        drizzle,
        connection: config.get('DATABASE_URL', { infer: true }),
      }),
    }),
    AuthenticationModule.forRootAsync({
      inject: [ConfigService],
      useFactory: (config: ConfigService<Env, true>) => ({
        accessToken: {
          key: config.get('JWT_SECRET', { infer: true }),
          issuer: 'blog-api',
          audience: 'blog-api',
          ttl: '15m',
        },
        refreshToken: { ttl: '30d', absoluteTtl: '90d' },
      }),
    }),
    GraphQLModule.forRootAsync<ApolloDriverConfig>({
      driver: ApolloDriver,
      useClass: GraphqlConfig,
    }),
    ThrottlerModule.forRoot([
      // 按 IP 地址，作用于让用户登录的变更。
      { name: 'default', ttl: minutes(1), limit: 100 },
      // 按邮箱和 IP 地址，作用于变更的输入指明账号的所有情况。
      {
        name: 'account',
        ttl: minutes(15),
        limit: 5,
        skipIf: (context) => !accountEmail(context),
        getTracker: (req, context) => `${accountEmail(context)}|${normalizeIp(req.ip)}`,
      },
    ]),
    UsersModule,
    AuthModule,
    PostsModule,
  ],
  providers: [
    { provide: APP_PIPE, useValue: new ValidationPipe({ transform: true, exceptionFactory: badUserInput }) },
    { provide: APP_FILTER, useClass: GraphQLErrorFilter },
  ],
})
export class AppModule {}
```

- **`ObserveModule` 放在 `imports` 的最前面**，与 [SDK 快速入门](/observability/sdk#quick-start) 一致：模块按相反顺序关闭，因此它最后停止，并发送其他模块记录的内容（参见[关闭](/observability/sdk#shutdown)）。`createObserveModule()` 把它与 `ObserveInstrument` 一起返回，`main.ts` 会把后者传给 Nest。
- **在关联项目之前，密钥对为空。** 没有密钥对时，SDK 不发送任何内容，并在启动时说明这一点。`npx @nestjs/observe link` 会把 `OBSERVE_APP_KEY` 和 `OBSERVE_APP_SECRET` 写入 `.env`，并向 `start` 脚本加上 `--env-file .env`，因此它们在 `AppModule` 被导入（SDK 读取它们）之前就已进入环境（参见[从终端关联](/observability/sdk#linking-from-the-terminal)）。
- **`transform: true`** 让参数成为其类的实例，这是 class-validator 所需要的。管道和过滤器是 `AppModule` 的提供者，因此测试也会得到它们。

`main.ts` 在 Node 适配器上创建应用，第三个参数是选项，其中包含 `instrument`：

```typescript
@@filename(src/main)
import { ConsoleLogger } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { NestFactory } from '@nestjs/core';
import { NodeAdapter, type NestNodeApplication } from '@nestjs/platform-node';
import { AppModule, ObserveInstrument } from './app.module.js';
import type { Env } from './config.js';

const production = process.env.NODE_ENV === 'production';
const app = await NestFactory.create<NestNodeApplication>(AppModule, new NodeAdapter(), {
  instrument: ObserveInstrument,
  logger: new ConsoleLogger({
    // 生产环境中每行一个 JSON 对象；开发环境中为可读文本。
    json: production,
    // 这些属性出现在被记录的对象中时一律掩码。
    redact: ['password', 'authorization', 'accessToken', 'refreshToken'],
  }),
});
app.useSecurityHeaders({
  // GraphiQL 仅在生产环境之外提供，它从 unpkg.com 加载脚本。
  contentSecurityPolicy: production
    ? true
    : { directives: { scriptSrc: ["'self'", "'unsafe-inline'", 'https://unpkg.com'] } },
});
app.enableShutdownHooks();

const config = app.get<ConfigService<Env, true>>(ConfigService);
app.enableCors({ origin: config.get('CORS_ORIGINS', { infer: true }) });

await app.listen(config.get('PORT', { infer: true }));
```

生产环境中日志为 JSON，密码和令牌会被掩码（参见 [JSON 日志](/application/logger#json-logging)）。生产环境之外为 GraphiQL 放宽了安全策略，因为它从 `unpkg.com` 加载脚本（参见 [Swagger UI 与 GraphQL IDE](/security/helmet#swagger-ui-and-graphql-ides)）。CORS 只允许 `CORS_ORIGINS`（参见[默认允许的来源](/security/cors#default-allowed-origins)）。

#### 为数据库填充数据

一个脚本为博客添加两个用户、十二篇已发布文章、每人一篇草稿，以及评论：

```typescript
@@filename(src/database/seed)
import { PasswordHasher } from '@nestjs/authentication';
import { drizzle } from 'drizzle-orm/node-postgres';
import { envSchema } from '../config.js';
import { comments, posts, users } from './schema.js';

// 开发数据：清空各表，然后添加两个用户及其文章和评论。
const { NODE_ENV, DATABASE_URL } = envSchema.parse(process.env);
if (NODE_ENV === 'production') {
  throw new Error('Refusing to seed a production database');
}
const db = drizzle(DATABASE_URL);
const passwordHash = await new PasswordHasher().hash('correct horse battery');
await db.execute('TRUNCATE users, posts, comments, refresh_tokens');

const [ada, bob] = await db
  .insert(users)
  .values([
    { email: 'ada@example.com', name: 'Ada', passwordHash },
    { email: 'bob@example.com', name: 'Bob', passwordHash },
  ])
  .returning();
// 十二篇已发布文章，相隔一小时，由 Ada 和 Bob 轮流发布，每人另有一篇草稿。
const published = await db
  .insert(posts)
  .values(
    Array.from({ length: 12 }, (_, i) => ({
      authorId: [ada, bob][i % 2].id,
      title: `Post ${i + 1}`,
      body: `The body of post ${i + 1}.`,
      publishedAt: new Date(Date.now() - (12 - i) * 3_600_000),
    })),
  )
  .returning();
await db.insert(posts).values([
  { authorId: ada.id, title: "Ada's draft", body: 'Not ready yet.' },
  { authorId: bob.id, title: "Bob's draft", body: 'Not ready either.' },
]);
// 每篇文章一条评论，由另一位用户发表。
await db
  .insert(comments)
  .values(published.map((post) => ({ postId: post.id, authorId: post.authorId === ada.id ? bob.id : ada.id, body: `About ${post.title}` })));

console.log(`Seeded 2 users, ${published.length} published posts and 2 drafts`);
await db.$client.end();
```

向 `package.json` 添加一个脚本：

```json
"db:seed": "node --env-file-if-exists=.env dist/database/seed.js"
```

构建应用并填充数据：

```bash
$ npm run build
$ npm run db:seed
...
Seeded 2 users, 12 published posts and 2 drafts
```

#### 试一试

启动应用：

```bash
$ npm run start
```

开发环境中，GraphiQL 位于 `http://localhost:3000/graphql`，即 API 自己的 URL：在其请求头编辑器中添加一个 `Authorization` 请求头，就能以某个用户的身份运行操作。使用 curl 时，分别以 Ada 和 Bob 登录，并保留他们的访问令牌：

```bash
$ curl localhost:3000/graphql --json '{"query":"mutation ($input: SignInInput!) { signIn(input: $input) { accessToken refreshToken expiresIn } }","variables":{"input":{"email":"ada@example.com","password":"correct horse battery"}}}'
{"data":{"signIn":{"accessToken":"eyJhbGciOiJIUzI1NiIs...","refreshToken":"I-NorWBT--e6Jkit...","expiresIn":900}}}
$ ADA=eyJhbGciOiJIUzI1NiIs...
$ BOB=eyJhbGciOiJIUzI1NiIs... # 同上，改用 bob@example.com
```

第一页已发布文章，然后是下一页，它从 `endCursor` 之后开始：

```bash
$ curl localhost:3000/graphql --json '{"query":"{ posts(first: 2) { edges { node { title author { name email } comments(first: 1) { body } } } pageInfo { hasNextPage endCursor } } }"}'
{"data":{"posts":{"edges":[{"node":{"title":"Post 12","author":{"name":"Bob","email":null},"comments":[{"body":"About Post 12"}]}},...],"pageInfo":{"hasNextPage":true,"endCursor":"MTc5NTY3Njg0NzQzMTo3NTYwM2RiNC0xZjJlLTQ1MDYtOTVjNy0wNzM3MmY0NjdiMzc"}}}}
$ curl localhost:3000/graphql --json '{"query":"query ($after: String) { posts(first: 2, after: $after) { edges { node { title } } } }","variables":{"after":"MTc5NTY3Njg0NzQzMTo3NTYwM2RiNC0xZjJlLTQ1MDYtOTVjNy0wNzM3MmY0NjdiMzc"}}'
{"data":{"posts":{"edges":[{"node":{"title":"Post 10"}},{"node":{"title":"Post 9"}}]}}}
```

Ada 自己的列表以她的草稿开头。Bob 对它得到 `null`，与面对不存在的 id 时相同：

```bash
$ curl localhost:3000/graphql -H "Authorization: Bearer $ADA" --json '{"query":"{ me { posts(first: 2) { id title publishedAt } } }"}'
{"data":{"me":{"posts":[{"id":"5761230b-00cd-4fbd-aedc-7a751770daa9","title":"Ada's draft","publishedAt":null},{"id":"75603db4-1f2e-4506-95c7-07372f467b37","title":"Post 11",...}]}}}
$ curl localhost:3000/graphql -H "Authorization: Bearer $BOB" --json '{"query":"query ($id: ID!) { post(id: $id) { title } }","variables":{"id":"5761230b-00cd-4fbd-aedc-7a751770daa9"}}'
{"data":{"post":null}}
```

错误会带上代码：Bob 不能修改 Ada 的文章，标题也不能为 `null`。在开发环境中，`extensions` 还会带上堆栈：

```bash
$ curl localhost:3000/graphql -H "Authorization: Bearer $BOB" --json '{"query":"mutation ($id: ID!) { updatePost(input: { id: $id, title: \"Mine now\" }) { title } }","variables":{"id":"75603db4-1f2e-4506-95c7-07372f467b37"}}'
{"errors":[{"message":"Only the author can change this post",...,"extensions":{"code":"FORBIDDEN",...}}],"data":null}
$ curl localhost:3000/graphql -H "Authorization: Bearer $ADA" --json '{"query":"mutation ($id: ID!) { updatePost(input: { id: $id, title: null }) { title } }","variables":{"id":"75603db4-1f2e-4506-95c7-07372f467b37"}}'
{"errors":[{"message":"title must be longer than or equal to 1 characters; title must be a string",...,"extensions":{"code":"BAD_USER_INPUT","fields":{"title":[...]},...}}],"data":null}
```

一个短脚本用你传给它的令牌监听某篇文章的评论：

```typescript
@@filename(scripts/watch-comments)
// 文章新增评论到达时打印出来：node scripts/watch-comments.ts <postId> <accessToken>
import { createClient } from 'graphql-ws';

const [postId, accessToken] = process.argv.slice(2);
const client = createClient({
  url: process.env.WS_URL ?? 'ws://localhost:3000/graphql',
  // 在套接字打开时发送一次。Node.js 22 像浏览器一样内置了 WebSocket 客户端。
  connectionParams: { authorization: `Bearer ${accessToken}` },
  retryAttempts: 0,
});

try {
  const comments = client.iterate({
    query: 'subscription ($postId: ID!) { commentAdded(postId: $postId) { body author { name } } }',
    variables: { postId },
  });
  for await (const result of comments) {
    console.log(JSON.stringify(result));
  }
} catch (error) {
  // 服务器关闭了套接字：拒绝令牌时为 4403。
  const { code, reason } = error as CloseEvent;
  console.error(`Closed: ${code} ${reason}`);
}
```

在第二个终端中运行它，传入 Ada 的 `Post 11` 的 id 和 Bob 的令牌，并在第一个终端中以 Ada 身份添加一条评论。脚本会把它打印出来；如果令牌不对，服务器会在任何订阅之前关闭套接字：

```bash
$ node scripts/watch-comments.ts 75603db4-1f2e-4506-95c7-07372f467b37 $BOB
{"data":{"commentAdded":{"body":"Thanks for reading!","author":{"name":"Ada"}}}}
$ node scripts/watch-comments.ts 75603db4-1f2e-4506-95c7-07372f467b37 not-a-token
Closed: 4403 Forbidden
```

以 Ada 身份从第一个终端添加的那条评论：

```bash
$ curl localhost:3000/graphql -H "Authorization: Bearer $ADA" --json '{"query":"mutation ($input: AddCommentInput!) { addComment(input: $input) { id } }","variables":{"input":{"postId":"75603db4-1f2e-4506-95c7-07372f467b37","body":"Thanks for reading!"}}}'
{"data":{"addComment":{"id":"c7ca2df6-811b-4292-9b9b-067281eab611"}}}
```

#### 测试

测试会在 PostgreSQL 测试数据库上启动真实的 `AppModule`，使用一个会统计所发送 SQL 语句的连接，并采用更低的 scrypt 成本。大多数测试用 Node 适配器提供的 `app.inject()` 发送操作；WebSocket 测试则监听一个端口：

```typescript
@@filename(test/test-app)
import { fileURLToPath } from 'node:url';
import { PasswordHasher } from '@nestjs/authentication';
import { getDrizzleToken } from '@nestjs/drizzle';
import { NodeAdapter, type NestNodeApplication } from '@nestjs/platform-node';
import { Test } from '@nestjs/testing';
import { sql } from 'drizzle-orm';
import { drizzle } from 'drizzle-orm/node-postgres';
import { migrate } from 'drizzle-orm/node-postgres/migrator';
import { Pool } from 'pg';

export interface TestApp {
  app: NestNodeApplication;
  /** 应用到目前为止发送了多少条 SQL 语句。 */
  sqlCount: () => number;
  close: () => Promise<void>;
}

/** 真实的 AppModule，运行在 TEST_DATABASE_URL 所指的数据库上，且先清空该库。 */
export async function createTestApp(): Promise<TestApp> {
  // 在这里导入，使测试文件能在模块读取它之前设置 NODE_ENV。
  const { AppModule } = await import('../src/app.module.js');
  const pool = new Pool({ connectionString: process.env.TEST_DATABASE_URL });
  let count = 0;
  const db = drizzle({ client: pool, logger: { logQuery: () => void count++ } });
  await migrate(db, { migrationsFolder: fileURLToPath(new URL('../drizzle', import.meta.url)) });
  await db.execute(sql`TRUNCATE users, posts, comments, refresh_tokens CASCADE`);

  const moduleRef = await Test.createTestingModule({ imports: [AppModule] })
    .overrideProvider(getDrizzleToken())
    .useValue(db)
    // 默认成本下，scrypt 每次哈希占用 128 MiB，耗时几百毫秒。
    .overrideProvider(PasswordHasher)
    .useValue(new PasswordHasher({ logN: 10 }))
    .compile();
  const app = moduleRef.createNestApplication<NestNodeApplication>(new NodeAdapter());
  await app.init();
  return {
    app,
    sqlCount: () => count,
    close: async () => {
      await app.close();
      await pool.end();
    },
  };
}

export interface GqlResult {
  data?: any;
  errors?: { message: string; path?: string[]; extensions: { code: string; [key: string]: unknown } }[];
}

let clients = 0;

/** 用 app.inject() 从自己的地址发送一个操作。 */
export async function gql(
  app: NestNodeApplication,
  query: string,
  { variables, token }: { variables?: Record<string, unknown>; token?: string } = {},
): Promise<GqlResult> {
  const res = await app.inject({
    method: 'POST',
    url: '/graphql',
    headers: token ? { authorization: `Bearer ${token}` } : {},
    payload: { query, variables },
    // 注册按 IP 地址限流：每个测试客户端都有自己的地址。
    remoteAddress: `10.0.0.${++clients}`,
  });
  return res.json();
}

export async function signUp(app: NestNodeApplication, name: string): Promise<{ accessToken: string; refreshToken: string }> {
  const { data } = await gql(app, 'mutation ($input: SignUpInput!) { signUp(input: $input) { accessToken refreshToken } }', {
    variables: { input: { email: `${name.toLowerCase()}@example.com`, name, password: 'correct horse battery' } },
  });
  return data.signUp;
}

/** 创建一篇文章，并发布它，除非它要保留为草稿。 */
export async function createPost(app: NestNodeApplication, token: string, title: string, publish = true): Promise<string> {
  const create = 'mutation ($input: CreatePostInput!) { createPost(input: $input) { id } }';
  const { id } = (await gql(app, create, { token, variables: { input: { title, body: '' } } })).data.createPost;
  if (publish) {
    await gql(app, 'mutation ($id: ID!) { publishPost(id: $id) { id } }', { token, variables: { id } });
  }
  return id;
}
```

测试配置为应用提供环境变量，并逐个运行各文件，因为它们共用同一个数据库：

```typescript
@@filename(vitest.config.e2e)
import { defineConfig } from 'vitest/config';

export default defineConfig({
  resolve: {
    // Node.js 为 @nestjs/graphql 和 Apollo Server 加载 graphql 的 CommonJS 构建；若不这样做，
    // Vite 会给被测代码 ES 模块构建，这是第二份副本，会拒绝该 schema。
    alias: [{ find: /^graphql$/, replacement: 'graphql/index.js' }],
  },
  test: {
    globals: true,
    root: './',
    include: ['test/**/*.e2e-spec.ts'],
    // 各文件共用一个测试数据库，每个文件都会先清空它。
    fileParallelism: false,
    env: {
      // 在启动时校验；测试会用自己的连接替换它。
      DATABASE_URL: 'postgres://unused-in-tests',
      JWT_SECRET: 'test-only-jwt-secret-of-at-least-32-bytes',
    },
  },
});
```

Vite 会把 `graphql` 解析为它的 ES 模块构建，而 Node.js 提供给 `@nestjs/graphql` 和 Apollo Server 的是 CommonJS 构建：两份副本，于是 `graphql-ws` 会以「Cannot use GraphQLSchema ... from another module or realm」失败。该别名让测试代码也使用 CommonJS 构建。下面完整给出三个测试：在所有路径上都隐藏的草稿、随文章增多而保持不变的 SQL 计数，以及没有有效令牌时被拒绝的 WebSocket：

```typescript
@@filename(test/blog.e2e-spec)
import type { AddressInfo } from 'node:net';
import { createClient } from 'graphql-ws';
import { createPost, createTestApp, gql, signUp, type GqlResult, type TestApp } from './test-app.js';

describe.skipIf(!process.env.TEST_DATABASE_URL)('Blog API (e2e)', () => {
  let t: TestApp;
  let wsUrl: string;
  let ada: string;
  let bob: string;

  beforeAll(async () => {
    t = await createTestApp();
    // 端口 0：由操作系统挑选一个空闲端口。
    await t.app.listen(Number(process.env.TEST_PORT ?? 0), '127.0.0.1');
    wsUrl = `ws://127.0.0.1:${(t.app.getHttpServer().address() as AddressInfo).port}/graphql`;
    ada = (await signUp(t.app, 'Ada')).accessToken;
    bob = (await signUp(t.app, 'Bob')).accessToken;
  });
  afterAll(() => t.close());

  const post = (token: string, title: string, publish?: boolean) => createPost(t.app, token, title, publish);
  const code = (result: GqlResult) => result.errors?.[0].extensions.code;
  const ids = (list: { id: string }[]) => list.map((item) => item.id);

  it('hides a draft from everyone but its author, through every path', async () => {
    const draft = await post(ada, 'Draft', false);
    const published = await post(ada, 'Published');
    const byId = 'query ($id: ID!) { post(id: $id) { id author { posts(first: 50) { id } } } }';
    expect((await gql(t.app, byId, { token: ada, variables: { id: draft } })).data.post.id).toBe(draft);

    for (const token of [bob, undefined]) {
      expect((await gql(t.app, byId, { token, variables: { id: draft } })).data.post).toBeNull();
      const list = await gql(t.app, '{ posts(first: 50) { edges { node { id } } } }', { token });
      expect(list.data.posts.edges.map((edge: any) => edge.node.id)).not.toContain(draft);
      const viaAuthor = await gql(t.app, byId, { token, variables: { id: published } });
      expect(ids(viaAuthor.data.post.author.posts)).toContain(published);
      expect(ids(viaAuthor.data.post.author.posts)).not.toContain(draft);
    }
    // 写入会返回 NOT_FOUND，与未知 id 相同：没人能得知该草稿存在。
    for (const mutation of [
      'mutation ($id: ID!) { updatePost(input: { id: $id, title: "Mine now" }) { id } }',
      'mutation ($id: ID!) { publishPost(id: $id) { id } }',
      'mutation ($id: ID!) { addComment(input: { postId: $id, body: "First!" }) { id } }',
    ]) {
      expect(code(await gql(t.app, mutation, { token: bob, variables: { id: draft } }))).toBe('NOT_FOUND');
    }
    expect(ids((await gql(t.app, '{ me { posts(first: 50) { id } } }', { token: ada })).data.me.posts)).toContain(draft);
  });

  it('batches nested fields: the number of SQL queries stays flat as the posts grow', async () => {
    const queriesFor = async () => {
      const before = t.sqlCount();
      const query = '{ posts(first: 50) { edges { node { author { name posts(first: 2) { id } } comments(first: 5) { author { name } } } } } }';
      const { data } = await gql(t.app, query);
      return { posts: data.posts.edges.length, queries: t.sqlCount() - before };
    };
    const addPosts = async (count: number) => {
      for (let i = 0; i < count; i++) {
        const postId = await post(i % 2 ? ada : bob, `Post ${i}`);
        await gql(t.app, 'mutation ($postId: ID!) { addComment(input: { postId: $postId, body: "Nice" }) { id } }', {
          token: i % 2 ? bob : ada,
          variables: { postId },
        });
      }
    };
    await addPosts(3);
    const few = await queriesFor();
    await addPosts(20);
    const many = await queriesFor();

    expect(many.posts).toBe(few.posts + 20);
    expect(many.queries).toBe(few.queries);
    // 最多是文章、它们的作者、作者的文章、评论及其作者。
    expect(many.queries).toBeLessThanOrEqual(5);
  });

  it('refuses a WebSocket without a valid token, before any operation', async () => {
    const postId = await post(ada, 'Guarded');
    for (const token of [undefined, 'not-a-jwt', `${ada}x`]) {
      const client = createClient({ url: wsUrl, connectionParams: { authorization: `Bearer ${token}` }, retryAttempts: 0 });
      const comments = client.iterate({ query: 'subscription ($postId: ID!) { commentAdded(postId: $postId) { body } }', variables: { postId } });
      // 客户端会以 CloseEvent 拒绝：4403 Forbidden。
      await expect(comments.next()).rejects.toMatchObject({ code: 4403 });
    }
  });
});
```

另外还有三个文件，与应用的其余部分一起位于[示例仓库](https://github.com/nestjs/example-graphql-api) 中，用来验证其余保证：

- `test/errors.e2e-spec.ts`：匿名变更得到 `UNAUTHENTICATED`，非作者的更新得到 `FORBIDDEN`，邮箱只会到达其所有者，无效参数得到带可读消息的 `BAD_USER_INPUT`，重复使用的刷新令牌连同它的后继令牌一起被拒绝。
- `test/subscriptions.e2e-spec.ts`：订阅者只收到自己那篇文章的评论，不会收到其他文章的；别人的草稿是 `NOT_FOUND`；套接字拒绝内省和变更。
- `test/production.e2e-spec.ts`：在导入 `AppModule` 之前把 `NODE_ENV` 设为 `production`，意外错误会被掩码，而有意抛出的错误保留其消息但不带堆栈。

向 `package.json` 添加一个脚本：

```json
"test:e2e": "vitest run --config ./vitest.config.e2e.ts"
```

先创建测试数据库，然后针对它运行各文件：

```bash
$ docker exec blog-db psql -U postgres -c "CREATE DATABASE blog_test"
$ TEST_DATABASE_URL=postgres://postgres:blog@localhost:5432/blog_test npm run test:e2e

 Test Files  4 passed (4)
      Tests  12 passed (12)
```

每个测试在没有它所保护的代码时都会失败。三个加载器中任何一个没有 DataLoader，SQL 计数就会随文章增多而增长。没有 `onConnect`，不带令牌的套接字也能打开。没有 `onSubscribe`，内省查询和变更就能通过套接字运行。

#### 生产环境检查清单

- **将 `NODE_ENV` 设为 `production`。** 此时认证模块在没有刷新令牌存储的情况下会拒绝启动，并且：
  - 内省会被拒绝，错误码为 `GRAPHQL_VALIDATION_FAILED`：HTTP 上由 Apollo Server 拒绝，套接字上同样拒绝，因为套接字只提供订阅。
  - `/graphql` 不再提供 GraphiQL，且 Apollo Server 的 CSRF 防护会对其他站点页面无需预检即可发出的请求（例如 `text/plain` 的 POST）返回 400。
  - 错误不带堆栈，`formatError` 会把意外错误的消息替换为 `Internal server error`。
- **把 `JWT_SECRET` 保存在平台的密钥存储中**，在运行时注入；并把 `drizzle-kit migrate` 作为发布步骤，在新版本启动之前运行。
- **在运行第二个实例之前替换内存中的 `PubSub`**：在一个实例上添加的评论永远不会到达连接到另一个实例的订阅者。改用由 Redis 或其他消息代理支持的实现（参见 [`PubSub` 实现](https://github.com/apollographql/graphql-subscriptions#pubsub-implementations)），为限流器提供共享[存储](/security/rate-limiting#storages)，并确保负载均衡器转发 `/graphql` 上的 WebSocket 升级请求。
- **位于负载均衡器之后时，向 `NodeAdapter` 传入 `trustProxy`**（参见[Node 适配器选项](/http/performance#node-adapter-options)），让限流器看到客户端地址。
- **把 `CORS_ORIGINS` 设为你的 Web 应用的来源**；如果没有浏览器调用该 API，就留空。
- **用平台的日志驱动从 stdout 收集 JSON 日志。**
- **为生产环境提供它自己的 Observe 密钥对**，在项目的 **API Keys** 页面获取，并以 `OBSERVE_APP_KEY` 和 `OBSERVE_APP_SECRET` 放入平台的环境变量中：`start:prod` 不会加载 `.env`。随后 [NestJS Observe](/observability/overview) 会按操作拆分展示 GraphQL 请求（参见[遥测视图](/observability/dashboard#telemetry-views)），记录每个解析器，并捕获从解析器向外传播的错误（参见[错误监控](/observability/error-monitoring)）。它需要 `@nestjs/graphql` 13.4.4 或更高版本，其 `graphql` 选项会为操作的用户打标签、忽略或命名（参见[塑造记录内容](/observability/sdk#shaping-what-is-recorded)）。

#### 下一步

- 用权限而不是所有权来决定每个用户能做什么：[授权](/security/authorization)。
- 把 schema 拆分到多个服务：[联邦](/graphql/federation)。
- 让构建过程从 TypeScript 类型添加 `@Field()` 元数据：[CLI 插件](/graphql/cli-plugin)。
- 用 REST 构建同类的 API：[使用 JWT 认证构建 REST API](/tutorials/rest-api-jwt-authentication)。
