如何在已有属性的NestJS DTO类中添加additionalProperties: false
解决方案:通过类级Swagger装饰器实现DTO的额外属性禁用
可以通过在DTO类上添加@Schema装饰器并配置additionalProperties: false来实现需求,无需在控制器中逐个定义schema,完全依赖nestjs/swagger的装饰器即可满足要求,具体步骤如下:
- 导入并使用
@Schema装饰器
从@nestjs/swagger中导入@Schema装饰器,直接在目标DTO类上配置禁用额外属性:
import { ApiProperty, Schema } from '@nestjs/swagger'; @Schema({ additionalProperties: false }) export class SomeResponseDto { @ApiProperty() id: string; @ApiProperty() text: string; }
- 控制器中正常引用DTO
在控制器的@ApiResponse中直接指定type为该DTO类即可,无需额外配置schema:
import { Controller, Get } from '@nestjs/common'; import { ApiResponse, ApiTags } from '@nestjs/swagger'; import { SomeResponseDto } from './some-response.dto'; @ApiTags('demo') @Controller('demo') export class DemoController { @Get() @ApiResponse({ status: 200, type: SomeResponseDto }) getDemo(): SomeResponseDto { return { id: '1', text: 'test' }; } }
- 复用规则的自定义装饰器(可选)
如果需要在多个DTO中复用"禁用额外属性"的规则,可以封装一个自定义装饰器:
import { Schema, SchemaOptions } from '@nestjs/swagger'; // 封装默认禁用额外属性的装饰器,可传入其他Schema配置 export const StrictSchema = (options?: Omit<SchemaOptions, 'additionalProperties'>) => Schema({ ...options, additionalProperties: false });
使用时替换@Schema为@StrictSchema()即可:
@StrictSchema() export class SomeResponseDto { // ...属性定义 }
效果说明
生成的OpenAPI schema中,SomeResponseDto的定义会自动包含additionalProperties: false,express-openapi-validator会基于此规则校验响应,一旦返回包含额外属性的内容就会触发校验错误。
注意:确保你的@nestjs/swagger版本在5.x及以上,该版本开始支持@Schema装饰器的additionalProperties配置项。
内容的提问来源于stack exchange,提问作者ttemple
相关产品推荐
相关产品推荐

