如何避免在 NestJs-swagger 的每个 dto 中写入 `@ApiProperty()`

Dan*_*nik 8 javascript swagger typescript nestjs nestjs-swagger

我正在研究如何避免在每个 dto 中指定 @ApiProperty() 的方法。

我知道存在一种创建 file 的方法nest-cli.json,如果您Promise<DTO>在 Nest-swagger 的控制器中指定,它将从路由生成输出 dto 。

结构如下:

nest-cli.json

{
  "collection": "@nestjs/schematics",
  "sourceRoot": "src",
  "compilerOptions": {
    "plugins": [
      {
        "name": "@nestjs/swagger",
        "options": {
          "introspectComments": true
        }
      }
    ]
  }
}
Run Code Online (Sandbox Code Playgroud)

controller.ts

@Get()
  async getMonitors (): Promise<OutputMonitorsDto> { // <-- Here is my outputDto
    return this.monitorsService.getMonitors()
  }
Run Code Online (Sandbox Code Playgroud)

它大摇大摆地显示了这样的东西: 在此输入图像描述

但是,有没有办法将 NestJs 设置为与 inputDTO 具有相同的内容,而不是在每个 dto 中写入@ApiProperty

如下例所示:

ExampleDto.ts

export class GetListUsersDto {
  @ApiProperty()
  @IsString()
  name: string
  @ApiProperty()
  @IsString()
  email: string
  @ApiProperty()
  @IsString()
  publicApiKey: string
  @ApiProperty()
  @IsBoolean()
  isAdmin: boolean
  @ApiProperty()
  @IsBoolean()
  isDesigner: boolean
  @ApiProperty()
  @IsBoolean()
  isEditor: boolean
  @ApiProperty()
  @IsBoolean()
  isEnabled: boolean
  @ApiProperty()
  @IsString()
  boughtProduct: string
}
Run Code Online (Sandbox Code Playgroud)

并且只有在 @ApiProperty 之后,它才会显示如上所示的结构,用于 swagger 中的输入。

Ant*_*rdi 7

没有办法可以装饰您的 DTO 属性。但是,如果您的 DTO 有很多共同点,您可能会寻找映射类型可以在此处找到文档。

这些本质上允许您转换现有类型以保持 DTO 干燥。


Dei*_*rez 5

如果您使用 cli-plugin,则不需要添加 @ApiProperty。检查文档openapi/cli-plugin

尝试这个

export class CreateUserDto {
  email: string;
  password: string;
  roles: RoleEnum[] = [];
  @IsOptional()
  isEnabled?: boolean = true;
}
Run Code Online (Sandbox Code Playgroud)


tte*_*ple 5

使用该插件为我解决了这个问题,请参阅https://docs.nestjs.com/openapi/cli-plugin#using-the-cli-plugin

要启用该插件,请打开nest-cli.json(如果您使用 Nest CLI)并添加以下插件配置:

{
  "collection": "@nestjs/schematics",
  "sourceRoot": "src",
  "compilerOptions": {
    "plugins": ["@nestjs/swagger"]
  }
}
Run Code Online (Sandbox Code Playgroud)

然后这将自动应用 @ApiProperty() 而无需添加它

export class CreateUserDto {
  email: string;
  password: string;
  roles: RoleEnum[] = [];
  @IsOptional()
  isEnabled?: boolean = true;
}
Run Code Online (Sandbox Code Playgroud)