自动为 dto 生成 @ApiProperty ()#
nest-cli.json
文件中新增 compilerOptions.plugins
:
// https://docs.nestjs.com/openapi/cli-plugin
{
"collection": "@nestjs/schematics",
"sourceRoot": "src",
"compilerOptions": {
"assets": [
"assets/**/*"
],
"plugins": [
{
"name": "@nestjs/swagger",
"options": {
"classValidatorShim": true,
"introspectComments": true
}
}
]
}
}
枚举属性#
// 这样会渲染出一个单选下拉菜单,多选设置 isArray: true
@ApiProperty({
enum: enumUtils.toObject(AppKind),
enumName: 'AppKind',
description: JSON.stringify(enumUtils.toObject(AppKind)),
})
kind: AppKind;
文件上传#
// controller
@ApiConsumes('multipart/form-data')
@ApiBody({ type: AppReleaseBodyDto })
@ApiBearerAuth()
// upload a file and data in a request:https://stackoverflow.com/a/61165115/7712266
@UseInterceptors(FilesInterceptor('files'))
@HttpCode(HttpStatus.OK)
@Post('release')
release(
@UploadedFiles()
files: Express.Multer.File[],
@Body() body: AppReleaseBodyDto,
) {
return this.appService.release(files, body);
}
// AppReleaseBodyDto
export class AppReleaseBodyDto {
// 这个仅仅是为了生成 sawgger 文档而增加的属性,实际上这个属性是由 controller 中的 params 接收的
// 单文件
// @Allow()
// @ApiProperty({ type: 'string', format: 'binary' })
// file: any;
// 多文件
@Allow()
@ApiProperty({ type: 'array', items: { type: 'string', format: 'binary' } })
files: any[];
}
多类型字段#
@ApiExtraModels(
DeviceBodyBedCallerValueDto,
DeviceBodyDoorLightValueDto,
DeviceBodyIntercomExtensionValueDto,
DeviceBodyLatticeAisleDisplayValueDto,
DeviceBodyMedicalGasDetectorValueDto,
DeviceBodyToiletCallerValueDto,
)
export class DeviceCreateBodyDto {
// https://github.com/nestjs/swagger/issues/852#issuecomment-1034934426
// https://docs.nestjs.com/openapi/types-and-parameters#oneof-anyof-allof
@ApiProperty({
oneOf: [
{ $ref: getSchemaPath(DeviceBodyBedCallerValueDto) },
{ $ref: getSchemaPath(DeviceBodyDoorLightValueDto) },
{ $ref: getSchemaPath(DeviceBodyIntercomExtensionValueDto) },
{ $ref: getSchemaPath(DeviceBodyLatticeAisleDisplayValueDto) },
{ $ref: getSchemaPath(DeviceBodyMedicalGasDetectorValueDto) },
{ $ref: getSchemaPath(DeviceBodyToiletCallerValueDto) },
],
})
@ValidateNested()
@Type(() => DeviceBodyValueDto, {
keepDiscriminatorProperty: true,
discriminator: {
property: 'kind',
subTypes: [
{
name: DeviceKind.床位呼叫器.toString(),
value: DeviceBodyBedCallerValueDto,
},
{
name: DeviceKind.门灯.toString(),
value: DeviceBodyDoorLightValueDto,
},
{
name: DeviceKind.对讲分机.toString(),
value: DeviceBodyIntercomExtensionValueDto,
},
{
name: DeviceKind.过道显示器.toString(),
value: DeviceBodyLatticeAisleDisplayValueDto,
},
{
name: DeviceKind.医气检测仪.toString(),
value: DeviceBodyMedicalGasDetectorValueDto,
},
{
name: DeviceKind.卫生间呼叫器.toString(),
value: DeviceBodyToiletCallerValueDto,
},
],
},
})
@IsNotEmptyObject()
value: DeviceBodyTValueDto;
}
其它#
- 如果某个 controller.action 上加了 @ApiBody ({type: AppReleaseBodyDto}) ,那么 dto 文件中每个属性都需要手动写 @ApiProperty () 修饰符,因为这个加上了之后,nest-cli.json 配置的自动生成,就会忽略这个 action.
- nest-cli.json 中配置的自动为属性生成修饰符,很坑,特别是在使用 mapped-types 继承之后,很多需要手动加
- 对于数组类型的字段也无法自动生成