# CLI 插件

来源：https://docs.nestjs.com/openapi/cli-plugin

[TypeScript](https://www.typescriptlang.org/docs/handbook/decorators.html) 的元数据反射系统存在若干限制。例如，它无法确定一个类由哪些属性组成，也无法判断某个给定属性是可选的还是必需的。不过，其中一些限制可以在编译期得到解决。Nest 提供了一个插件，它增强 TypeScript 的编译过程，以减少所需的样板代码。

> info **提示** 该插件是 **选择启用** 的。如果你愿意，也可以手动声明全部装饰器，或只在需要的地方声明特定装饰器。

#### 概述

Swagger 插件会自动完成以下事情：

- 为所有 DTO 属性标注 `@ApiProperty()`，除非使用了 `@ApiHideProperty()`
- 根据问号设置 `required` 属性（例如 `name?: string` 会设置 `required: false`）
- 根据类型设置 `type` 或 `enum` 属性（也支持数组）
- 根据所赋的默认值设置 `default` 属性
- 根据 `class-validator` 装饰器设置若干校验规则（若 `classValidatorShim` 设为 `true`）
- 为每个端点添加响应装饰器，并带上合适的状态码和 `type`（响应模型）
- 根据注释为属性和端点生成描述（若 `introspectComments` 设为 `true`）
- 根据注释为属性生成示例值（若 `introspectComments` 设为 `true`）

要让插件分析某个 DTO 文件，其文件名 **必须包含** 下列后缀之一：`['.dto.ts', '.entity.ts']`（例如 `create-user.dto.ts`）。

如果你使用了其他后缀，请通过 `dtoFileNameSuffix` 选项调整插件的行为（见下文）。

不使用插件时，要为 Swagger UI 提供交互式体验，就得重复大量代码，去告诉这个包你的模型／组件在规范中应当如何声明。例如，你可能这样定义一个简单的 `CreateUserDto` 类：

```typescript
export class CreateUserDto {
  @ApiProperty()
  email: string;

  @ApiProperty()
  password: string;

  @ApiProperty({ enum: RoleEnum, default: [], isArray: true })
  roles: RoleEnum[] = [];

  @ApiProperty({ required: false, default: true })
  isEnabled?: boolean = true;
}
```

在中等规模的项目中这还不算大问题，但一旦类多起来，代码就会变得冗长、难以维护。

[启用 Swagger 插件](/openapi/cli-plugin#using-the-cli-plugin) 之后，上面的类可以不带任何装饰器直接声明：

```typescript
export class CreateUserDto {
  email: string;
  password: string;
  roles: RoleEnum[] = [];
  isEnabled?: boolean = true;
}
```

> info **注意** Swagger 插件根据 TypeScript 类型和 `class-validator` 装饰器推导出 `@ApiProperty()` 注解，这些注解在生成的 Swagger UI 文档中描述你的 API。不过，运行时校验仍由 `class-validator` 装饰器负责，因此你必须继续使用 `IsEmail()`、`IsNumber()` 这类校验器。

换句话说，如果你既依赖自动注解生成文档，又想要运行时校验，那么仍然需要 `class-validator` 装饰器。

> info **提示** 在 DTO 中使用[映射类型工具](/openapi/mapped-types)（例如 `PartialType`）时，请从 `@nestjs/swagger` 而不是 `@nestjs/mapped-types` 导入，这样插件才能识别出 schema。

插件基于 **抽象语法树** 即时添加合适的装饰器，因此你不必在代码里到处散落 `@ApiProperty()` 装饰器。

> info **提示** 插件会生成所有缺失的 Swagger 属性。要覆盖某一项，请通过 `@ApiProperty()` 显式设置。

#### 注释自省

启用注释自省（comments introspection）功能后，CLI 插件会根据注释为属性生成描述和示例值。

例如，看下面这个 `roles` 属性：

```typescript
/**
 * 用户的角色列表
 * @example ['admin']
 */
@ApiProperty({
  description: `A list of user's roles`,
  example: ['admin'],
})
roles: RoleEnum[] = [];
```

你必须把描述和示例值都重复写一遍。启用 `introspectComments` 后，CLI 插件会自动提取这些注释，并为属性提供描述（以及已定义的示例）。于是上面的属性可以这样声明：

```typescript
/**
 * 用户的角色列表
 * @example ['admin']
 */
roles: RoleEnum[] = [];
```

`dtoKeyOfComment` 与 `controllerKeyOfComment` 两个插件选项，分别用于自定义插件如何把注释值赋给 `ApiProperty` 和 `ApiOperation` 装饰器。见下例：

```typescript
export class SomeController {
  /**
   * 创建某个资源
   */
  @Post()
  create() {}
}
```

这等价于下面这样：

```typescript
@ApiOperation({ summary: "Create some resource" })
```

> info **提示** 对模型而言逻辑相同，只是改用 `ApiProperty` 装饰器。

对控制器而言，你不仅能提供摘要，还可以提供描述（remarks）、标签（例如 `@deprecated`）以及响应示例，如下所示：

```ts
/**
 * 创建一个新 cat
 *
 * @remarks 此操作允许你创建一只新 cat。
 *
 * @deprecated
 * @throws {500} 出现了错误。
 * @throws {400} 请求无效。
 */
@Post()
async create(): Promise<Cat> {}
```

自 `@nestjs/swagger` v12 起，插件（在启用 `introspectComments` 时）也会识别 `@param` 标签，因此路由参数的描述可以来自同一段文档注释：

```ts
/**
 * 列出 cat
 *
 * @param breed 按品种筛选结果
 * @param limit 返回结果的最大数量
 */
@Get()
findAll(@Query('breed') breed?: string, @Query('limit') limit?: number) {}
```

对于插件本就会为可选 `@Query()` 参数生成的 `@ApiQuery()`，它会补上 `description`；对于已记录文档的必需查询参数，它会生成 `@ApiQuery({{ '{' }} name, description &#125;)`；对于已记录文档的 `@Param()` 参数，它会生成 `@ApiParam({{ '{' }} name, description &#125;)`。

描述按 **变量名** 匹配，也就是 `@param` 所记录的那个名字。因此 `@Query('order_by') orderBy: string` 应记录为 `@param orderBy ...`，而不是 `@param order_by ...`。显式的 `@ApiQuery()` / `@ApiParam()` 装饰器始终优先，永远不会被覆盖。

#### 使用 CLI 插件

要启用插件，请打开 `nest-cli.json`（如果你使用 [Nest CLI](/cli/overview)），并添加如下 `plugins` 配置：

```javascript
{
  "collection": "@nestjs/schematics",
  "sourceRoot": "src",
  "compilerOptions": {
    "plugins": ["@nestjs/swagger"]
  }
}
```

使用 `options` 属性自定义插件的行为：

```javascript
{
  "collection": "@nestjs/schematics",
  "sourceRoot": "src",
  "compilerOptions": {
    "plugins": [
      {
        "name": "@nestjs/swagger",
        "options": {
          "classValidatorShim": false,
          "introspectComments": true,
          "skipAutoHttpCode": true
        }
      }
    ]
  }
}
```

`options` 属性接受以下选项（以及其他选项）：

```typescript
export interface PluginOptions {
  dtoFileNameSuffix?: string | string[];
  controllerFileNameSuffix?: string | string[];
  classValidatorShim?: boolean;
  classTransformerShim?: boolean | 'exclusive';
  dtoKeyOfComment?: string;
  controllerKeyOfComment?: string;
  introspectComments?: boolean;
  skipAutoHttpCode?: boolean;
  skipDefaultValues?: boolean;
  autoFillEnumName?: boolean;
  esmCompatible?: boolean;
}
```

<table>
  <tr>
    <th>选项</th>
    <th>默认值</th>
    <th>描述</th>
  </tr>
  <tr>
    <td><code>dtoFileNameSuffix</code></td>
    <td><code>['.dto.ts', '.entity.ts']</code></td>
    <td>DTO（数据传输对象）文件后缀</td>
  </tr>
  <tr>
    <td><code>controllerFileNameSuffix</code></td>
    <td><code>['.controller.ts']</code></td>
    <td>控制器文件后缀</td>
  </tr>
  <tr>
    <td><code>classValidatorShim</code></td>
    <td><code>true</code></td>
    <td>若设为 <code>true</code>，插件会复用 <code>class-validator</code> 的校验装饰器（例如 <code>@Max(10)</code> 会在 schema 定义中加入 <code>max: 10</code>）</td>
  </tr>
  <tr>
    <td><code>classTransformerShim</code></td>
    <td><code>false</code></td>
    <td>若设为 <code>true</code>，插件会跳过带 <code>class-transformer</code> 的 <code>@Exclude()</code> 装饰的属性。若设为 <code>'exclusive'</code>，则只记录带 <code>@Expose()</code> 或 <code>@ApiProperty()</code> 装饰的属性</td>
  </tr>
  <tr>
    <td><code>dtoKeyOfComment</code></td>
    <td><code>'description'</code></td>
    <td>在 <code>ApiProperty</code> 上承载注释文本的属性键。</td>
  </tr>
  <tr>
    <td><code>controllerKeyOfComment</code></td>
    <td><code>'summary'</code></td>
    <td>在 <code>ApiOperation</code> 上承载注释文本的属性键。</td>
  </tr>
  <tr>
    <td><code>introspectComments</code></td>
    <td><code>false</code></td>
    <td>若设为 <code>true</code>，插件会根据注释为属性生成描述和示例值</td>
  </tr>
  <tr>
    <td><code>skipAutoHttpCode</code></td>
    <td><code>false</code></td>
    <td>禁止在控制器中自动添加 <code>@HttpCode()</code></td>
  </tr>
  <tr>
    <td><code>skipDefaultValues</code></td>
    <td><code>false</code></td>
    <td>若设为 <code>true</code>，插件不会从属性初始化器设置 <code>default</code> 属性</td>
  </tr>
  <tr>
    <td><code>autoFillEnumName</code></td>
    <td><code>false</code></td>
    <td>若设为 <code>true</code>，对于未声明 <code>enumName</code> 的枚举属性，插件会把 <code>enumName</code> 设为该枚举类型的名称</td>
  </tr>
  <tr>
    <td><code>esmCompatible</code></td>
    <td>按文件检测</td>
    <td>使生成的代码兼容 ESM（<code>&#123; "type": "module" &#125;</code>）。省略该项时，插件会根据你的编译选项和 <code>package.json</code> 判断每个文件是否以 ESM 形式产出</td>
  </tr>
</table>

每次更新插件选项后，都要删除 `/dist` 文件夹并重新构建应用。

如果你不使用 CLI，而是有自己的 `webpack` 配置，可以把该插件与 `ts-loader` 配合使用：

```javascript
getCustomTransformers: (program: any) => ({
  before: [require('@nestjs/swagger/plugin').before({}, program)]
}),
```

#### SWC 构建器

对于标准（非 monorepo）配置，在 SWC 构建器下使用 CLI 插件需要启用类型检查，具体见 [SWC 方案](/recipes/swc#type-checking)。

```bash
$ nest start -b swc --type-check
```

对于 monorepo 配置，请按 [monorepo 与 CLI 插件](/recipes/swc#monorepo-and-cli-plugins) 的说明创建一个 `generate-metadata.ts` 文件，然后运行它：

```bash
$ npx ts-node src/generate-metadata.ts
# 或 npx ts-node apps/{YOUR_APP}/src/generate-metadata.ts
```

然后使用 `SwaggerModule#loadPluginMetadata()` 方法加载序列化后的元数据文件，如下所示：

```typescript
import metadata from './metadata.js'; // <-- 由 "PluginMetadataGenerator" 自动生成的文件

await SwaggerModule.loadPluginMetadata(metadata); // <-- 在此处
const document = SwaggerModule.createDocument(app, config);
```

#### 与 `ts-jest` 集成（e2e 测试）

运行 e2e 测试时，`ts-jest` 会在内存中即时编译你的源代码文件。这意味着它不使用 Nest CLI 的编译器，也不会应用任何插件或执行 AST 转换。

要启用该插件，请在 e2e 测试目录中创建如下文件：

```javascript
const transformer = require('@nestjs/swagger/plugin');

module.exports.name = 'nestjs-swagger-transformer';
// 只要改动下面的配置，就要同时修改版本号 —— 否则 jest 检测不到变化
module.exports.version = 1;

module.exports.factory = (cs) => {
  return transformer.before(
    {
      // @nestjs/swagger/plugin 选项（可以为空）
    },
    cs.program, // 旧版 Jest（<= v27）请用 "cs.tsCompiler.program"
  );
};
```

完成这一步后，在你的 `jest` 配置文件中引入该 AST 转换器。默认情况下（在起始应用中），e2e 测试配置文件位于 `test` 文件夹内，名为 `jest-e2e.json`。

如果你使用 `jest@<29`，请使用下面的片段：

```json
{
  ... // 其他配置
  "globals": {
    "ts-jest": {
      "astTransformers": {
        "before": ["<path to the file created above>"]
      }
    }
  }
}
```

如果你使用 `jest@^29`，请改用下面的片段，因为前一种方式已被废弃：

```json
{
  ... // 其他配置
  "transform": {
    "^.+\\.(t|j)s$": [
      "ts-jest",
      {
        "astTransformers": {
          "before": ["<path to the file created above>"]
        }
      }
    ]
  }
}
```

#### `jest` 疑难排查（e2e 测试）

如果 `jest` 似乎没有识别到你的配置变更，可能是 Jest **缓存** 了构建结果。要让新配置生效，请在 NestJS 项目文件夹中运行下面的命令清除 Jest 的缓存目录：

```bash
$ npx jest --clearCache
```

如果自动清除缓存失败，请用下面的命令手动删除缓存文件夹：

```bash
# 查找 jest 缓存目录（通常是 /tmp/jest_rs）
# 在 NestJS 项目根目录下运行下面的命令
$ npx jest --showConfig | grep cache
# 示例结果：
#   "cache": true,
#   "cacheDirectory": "/tmp/jest_rs"

# 删除或清空 Jest 缓存目录
$ rm -rf  <cacheDirectory value>
# 示例：
# rm -rf /tmp/jest_rs
```
