使用nest.js Controller中的class-validator使用class-validator的嵌套对象

问题描述 投票:0回答:3


import { IsNotEmpty, IsString, ValidateNested, IsNumber, IsDefined, } from 'class-validator'; class Data { @IsNotEmpty() @IsString() type: string; @IsNotEmpty() @IsNumber() id: number; } export class CurrencyDTO { @ValidateNested({ each: true }) @IsDefined() data: Data[]; }



在我的nest.js控制器中,我像这样使用它。

@Post() @UseGuards(new AuthTokenGuard()) @UsePipes(new ValidationPipe()) addNewCurrency(@Req() req, @Body() data: CurrencyDTO) { console.log('data', data); }

我的验证管类是这样的:

import { PipeTransform, Injectable, ArgumentMetadata, BadRequestException, HttpException, HttpStatus, } from '@nestjs/common'; import { validate, IsInstance } from 'class-validator'; import { plainToClass, Exclude } from 'class-transformer'; @Injectable() export class ValidationPipe implements PipeTransform<any> { async transform(value: any, metadata: ArgumentMetadata) { if (value instanceof Object && this.isEmpty(value)) { throw new HttpException( `Validation failed: No Body provided`, HttpStatus.BAD_REQUEST, ); } const { metatype } = metadata; if (!metatype || !this.toValidate(metatype)) { return value; } const object = plainToClass(metatype, value); const errorsList = await validate(object); if (errorsList.length > 0) { const errors = []; for (const error of errorsList) { const errorsObject = error.constraints; const { isNotEmpty } = errorsObject; if (isNotEmpty) { const parameter = isNotEmpty.split(' ')[0]; errors.push({ title: `The ${parameter} parameter is required.`, parameter: `${parameter}`, }); } } if (errors.length > 0) { throw new HttpException({ errors }, HttpStatus.BAD_REQUEST); } } return value; } private toValidate(metatype): boolean { const types = [String, Boolean, Number, Array, Object]; return !types.find(type => metatype === type); } private isEmpty(value: any) { if (Object.keys(value).length > 0) { return false; } return true; } }

除了嵌套对象外,该验证管为所有验证管均正常工作。知道我在这里做错了什么? 我的身体有效载荷是这样的:
{
"data": [{
    "id": 1,
    "type": "a"
}]
}

trory用

@Type

指定嵌套类型
import { Type } from 'class-transformer';

export class CurrencyDTO {
  @ValidateNested({ each: true })
  @Type(() => Data)
  data: Data[];
}
node.js typescript validation nestjs class-validator
3个回答
101
投票
@Type

装饰器,您会告诉类转换器在您的

plainToClass
中调用

VaildationPipe
时,将class-transformer实例化。 

如果您使用的是内置

ValidationPipe
确保已设置选项
transform: true

至少在我的情况下,接受的答案需要更多信息。作为原样,如果键

data

在请求上不存在,则将无法运行验证。要获得全面验证尝试:

@IsDefined()
@IsNotEmptyObject()
@ValidateNested()
@Type(() => CreateOrganizationDto)
@ApiProperty()
organization: CreateOrganizationDto;
    

聚会迟到了... 您可以遵循此方法的方法,它将按预期工作。 我制作了一个自定义装饰器,以便在验证对象时只能使用一行代码,而不是两行:

11
投票
export function ValidateNestedType(type: () => any) { return function (target: object, propertyName: string) { ValidateNested({ each: true })(target, propertyName); Type(type)(target, propertyName); }; }

用法看起来像这样:

@InputType() export class CreateProductInput { @ValidateNestedType(() => ProductDetailsInput) product: ProductDetailsInput; ... }
    

0
投票
最新问题
© www.soinside.com 2019 - 2025. All rights reserved.