# CLI 插件

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

> warning **警告** 本章仅适用于代码优先（code first）方式。

TypeScript 的元数据反射系统存在若干限制，例如无法确定一个类由哪些属性构成，也无法判断某个属性是可选的还是必需的。不过，其中一些限制可以在编译期解决。Nest 提供了一个插件来增强 TypeScript 的编译过程，以减少所需的样板代码。

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

#### 概述

GraphQL 插件会自动完成以下工作：

- 为输入对象（input object）、对象类型（object type）与参数（args）类的所有属性标注 `@Field`，除非使用了 `@HideField`
- 根据问号设置 `nullable` 属性（例如 `name?: string` 会设置 `nullable: true`）
- 根据类型设置 `type` 属性（同样支持数组）
- 根据注释生成属性描述（如果 `introspectComments` 设为 `true`）

你的文件名 **必须** 带有以下后缀之一，才会被插件分析：`['.input.ts', '.args.ts', '.entity.ts', '.model.ts']`（例如 `author.entity.ts`）。如果使用其他后缀，请通过 `typeFileNameSuffix` 选项调整插件的行为（见下文）。

就前面介绍的内容而言，你不得不重复大量代码，才能告诉该包你的类型在 GraphQL 中应如何声明。例如，你可能会像下面这样定义一个 `Author` 类：

```typescript
@@filename(authors/models/author.model)
@ObjectType()
export class Author {
  @Field(type => ID)
  id: number;

  @Field({ nullable: true })
  firstName?: string;

  @Field({ nullable: true })
  lastName?: string;

  @Field(type => [Post])
  posts: Post[];
}
```

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

启用 GraphQL 插件后，上面的类定义可以改写为：

```typescript
@@filename(authors/models/author.model)
@ObjectType()
export class Author {
  @Field(type => ID)
  id: number;
  firstName?: string;
  lastName?: string;
  posts: Post[];
}
```

插件会基于 **抽象语法树**（Abstract Syntax Tree）即时添加恰当的装饰器，因此你无需在代码中到处散布 `@Field` 装饰器。

> info **提示** 插件会自动生成所有缺失的 GraphQL 属性。如果需要覆盖它们，请用 `@Field()` 显式设置。

#### 注释内省

启用注释内省（comments introspection）功能后，CLI 插件会基于注释为字段生成描述。

例如，考虑一个 `roles` 属性：

```typescript
/**
 * A list of user's roles
 */
@Field(() => [String], {
  description: `A list of user's roles`
})
roles: string[];
```

这里你必须重复一遍描述。启用 `introspectComments` 后，CLI 插件会提取这些注释，并自动为属性提供描述。上面的字段便可改写为：

```typescript
/**
 * A list of user's roles
 */
roles: string[];
```

#### 使用 CLI 插件

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

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

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

```javascript
{
  "collection": "@nestjs/schematics",
  "sourceRoot": "src",
  "compilerOptions": {
    "plugins": [
      {
        "name": "@nestjs/graphql",
        "options": {
          "typeFileNameSuffix": [".input.ts", ".args.ts"],
          "introspectComments": true
        }
      }
    ]
  }
}

```

`options` 属性接受以下选项：

```typescript
export interface PluginOptions {
  typeFileNameSuffix?: string | string[];
  introspectComments?: boolean;
  esmCompatible?: boolean;
  debug?: boolean;
}
```

<table>
  <tr>
    <th>选项</th>
    <th>默认值</th>
    <th>说明</th>
  </tr>
  <tr>
    <td><code>typeFileNameSuffix</code></td>
    <td><code>['.input.ts', '.args.ts', '.entity.ts', '.model.ts']</code></td>
    <td>包含 GraphQL 类型的文件后缀</td>
  </tr>
  <tr>
    <td><code>introspectComments</code></td>
    <td><code>false</code></td>
    <td>若设为 <code>true</code>，插件会基于注释为属性生成描述</td>
  </tr>
  <tr>
    <td><code>esmCompatible</code></td>
    <td>根据各文件的模块格式推断</td>
    <td>若设为 <code>true</code>，插件会输出兼容 ESM 的代码（不产生 <code>require()</code> 调用，并为相对导入追加输出扩展名）。</td>
  </tr>
  <tr>
    <td><code>debug</code></td>
    <td><code>false</code></td>
    <td>若设为 <code>true</code>，插件会记录诊断消息（例如发现未被导出的类型时）</td>
  </tr>
</table>

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

```javascript
getCustomTransformers: (program) => ({
  before: [require('@nestjs/graphql/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) 中的说明。

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

然后，在 `GraphQLModule` 配置中加载序列化后的元数据文件，如下所示：

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

GraphQLModule.forRoot<...>({
  ..., // 其他选项
  metadata,
}),
```

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

在启用该插件的情况下运行 e2e 测试时，你可能会遇到 schema 编译问题。例如，最常见的错误之一是：

```json
Object type <name> must define one or more fields.
```

出现这种情况，是因为 `jest` 配置中任何地方都没有导入 `@nestjs/graphql/plugin` 插件。

要解决这个问题，请在 e2e 测试目录中创建以下文件：

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

module.exports.name = 'nestjs-graphql-transformer';
// 每次修改下面的配置时，都应该更改版本号——否则 jest 将无法检测到变化
module.exports.version = 1;

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

完成上述配置后，在 `jest` 配置文件中导入该 AST 转换器。默认情况下（在初始应用中），e2e 测试配置文件位于 `test` 文件夹下，名为 `jest-e2e.json`。

```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>"]
        }
      }
    ]
  }
}
```
