繁体   English   中英

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

[英]How to avoid to write `@ApiProperty()` in each dto for NestJs-swagger

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

我知道有一种方法可以创建文件nest-cli.json ,如果您在 Nest-swagger 中的 controller 中指定Promise<DTO> ,它将产生从路由 Z78E6221F6393D1356668dDB398F1 到 CEDZF1 的方法。

结构如下所示:

nest-cli.json

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

controller.ts

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

在 swagger 中显示如下内容: 在此处输入图像描述

但是,有没有办法将 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
}

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

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

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

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

尝试这个

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM