[英]How to avoid to write `@ApiProperty()` in each dto for NestJs-swagger
I'm researching the way on how to avoid to specify @ApiProperty() in each dto.我正在研究如何避免在每个 dto 中指定 @ApiProperty()。
I know there is exist a way to create file nest-cli.json
, and if you specify Promise<DTO>
in your controller in nest-swagger it will produce the output dto from the route.我知道有一种方法可以创建文件
nest-cli.json
,如果您在 Nest-swagger 中的 controller 中指定Promise<DTO>
,它将产生从路由 Z78E6221F6393D1356668dDB398F1 到 CEDZF1 的方法。
The structure looks like this:结构如下所示:
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()
}
And in swagger it shows something like this:在 swagger 中显示如下内容:
However, is there any way to setup NestJs to have the same things with inputDTO and not to write in each dto @ApiProperty
?但是,有没有办法将 NestJs 设置为与 inputDTO 具有相同的东西,而不是在每个 dto
@ApiProperty
中写入?
As in example below:如下例所示:
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
}
And only after @ApiProperty it will show the structure as shown above for input in swagger.只有在@ApiProperty 之后,它才会显示如上所示的结构,用于 swagger 中的输入。
There is no way around decorating your DTO properties.没有办法装饰您的 DTO 属性。 However, if your DTOs have a lot in common, you might be looking for mapped types .
但是,如果您的 DTO 有很多共同点,您可能正在寻找映射类型。 Documentation can be found here .
文档可以在这里找到。
These essentially allow you to transform existing types to keep your DTOs DRY.这些本质上允许您转换现有类型以保持 DTO 干燥。
If you are using cli-plugin you don't need to add @ApiProperty.如果您使用的是 cli-plugin,则不需要添加 @ApiProperty。 Check docs openapi/cli-plugin
检查文档openapi/cli-plugin
try this尝试这个
export class CreateUserDto {
email: string;
password: string;
roles: RoleEnum[] = [];
@IsOptional()
isEnabled?: boolean = true;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.