NestJS使用IntersectionType组合DTO后验证与Swagger文档失效问题
NestJS 使用 IntersectionType 组合 DTO 后验证失效与 Swagger 文档异常问题
承接此前的问题,我尝试确保DTO组合后验证规则仍能生效,但使用@nestjs/swagger的IntersectionType组合DTO后出现以下问题:
1. 单个DTO验证正常
定义了AdminCodeDTO(要求AdminCode为1-999的必填数字)和DescriptionDTO(要求Description为3-20位的必填字符串),各自的单元测试均能返回预期的验证错误。
AdminCodeDTO 代码
import { IsNumber, Min, Max, IsDefined } from '@nestjs/class-validator'; import { ApiProperty, ApiResponseProperty } from '@nestjs/swagger'; export class AdminCodeDTO { @ApiProperty({ description: 'Sweda Administration Code used for time tracking that is not part of a mantis.', }) @ApiResponseProperty({ example: 5 }) @IsDefined() @IsNumber() @Min(1) @Max(999) public AdminCode: number; constructor(AdminCode?: number) { this.AdminCode = AdminCode; } }
DescriptionDTO 代码
import { IsDefined, IsString, MaxLength, MinLength } from '@nestjs/class-validator'; import { ApiProperty, ApiResponseProperty } from '@nestjs/swagger'; export class DescriptionDTO { @ApiProperty({ description: '', minLength: 3, maxLength: 20 }) @ApiResponseProperty({ example: 'Sick Day' }) @IsDefined() @IsString() @MaxLength(20) @MinLength(3) public Description: string; constructor(Description?: string) { this.Description = Description; } }
2. 组合DTO验证失效
使用IntersectionType组合上述两个DTO得到AdmininstrationCodesDTO,虽能正确定义字段,但单元测试中验证规则不生效,空构造实例的验证错误数量不符合预期。
组合DTO代码
import { IsDefined, IsString, MaxLength, MinLength } from '@nestjs/class-validator'; import { ApiProperty, ApiResponseProperty, IntersectionType} from '@nestjs/swagger'; import { AdminCodeDTO } from './admin-code-dto'; export class AdmininstrationCodesDTO extends IntersectionType( AdminCodeDTO, DescriptionDTO ) { constructor(AdminCode?: number, Description?: string) { this.AdminCode = AdminCode; this.Description = Description; } }
测试代码
import { AdmininstrationCodesDTO } from './admininstration-codes-dto'; describe('AdmininstrationCodesDTO', () => { let TestDTO: AdmininstrationCodesDTO; beforeEach( () => { TestDTO = new AdmininstrationCodesDTO(77, 'Test Admin Code'); }) it('should be defined', () => { expect(TestDTO).toBeDefined(); }); it('should be defined when launched without parameters', () => { expect(new AdmininstrationCodesDTO()).toBeDefined(); }) it.each([ ['AdminCode', 77], ['Description', 'Test Admin Code'], ])('should have the proper field {%s} set to be %d', (FieldName, Expected) => { expect(FieldName in TestDTO).toBe(true); expect(TestDTO[FieldName]).toBe(Expected); }); // 此测试失败,验证规则未生效 it('should generate the DTO errors', async () => { const TestDTO: AdmininstrationCodesDTO = new AdmininstrationCodesDTO(); const Errors: Array<ValidationError> = await validate(TestDTO); expect(Errors.length).toBe(8); }); });
3. Swagger文档异常
组合DTO的请求架构无法在Swagger UI中显示字段,而直接定义字段的DTO可正常显示(项目为NX monorepo,已启用CLI功能)。
内容的提问来源于stack exchange,提问作者Steven Scott
相关产品推荐
相关产品推荐

