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 中的输入。
如果您使用 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)
使用该插件为我解决了这个问题,请参阅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)
归档时间: |
|
查看次数: |
10670 次 |
最近记录: |