javascript - Como evitar escrever `@ApiProperty()` em cada DTO para NestJs-swagger
Estou pesquisando a forma de como evitar especificar @ApiProperty() em cada DTO.
Eu sei que existe uma maneira de criar o arquivo nest-cli.json, e se você especificar Promise<DTO> no seu controller no nest-swagger, ele irá produzir o dto de saída da rota.
A estrutura se parece com isto:
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()
}
E no Swagger ele mostra algo assim:
No entanto, existe alguma maneira de configurar o NestJs para ter as mesmas coisas com inputDTO e não precisar escrever em cada dto @ApiProperty?
Como no exemplo abaixo:
ExampleDto.tsexport 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
}
E somente após @ApiProperty ele mostrará a estrutura como mostrado acima para entrada no Swagger.
Resposta #1
Usar o plugin resolveu esse problema para mim, veja https://docs.nestjs.com/openapi/cli-plugin#using-the-cli-plugin.
Para habilitar o plugin, abra nest-cli.json (se você usar o Nest CLI) e adicione a seguinte configuração de plugins:
{
"collection": "@nestjs/schematics",
"sourceRoot": "src",
"compilerOptions": {
"plugins": ["@nestjs/swagger"]
}
}
Então isso aplicará automaticamente o @ApiProperty() sem precisar adicioná-lo
export class CreateUserDto {
email: string;
password: string;
roles: RoleEnum[] = [];
@IsOptional()
isEnabled?: boolean = true;
}
Resposta #2
Não há como evitar decorar suas propriedades DTO. No entanto, se seus DTOs tiverem muito em comum, você pode estar procurando por tipos mapeados. A documentação pode ser encontrada aqui.
Essencialmente, isso permite que você transforme tipos existentes para manter seus DTOs DRY.
