26

我想在 nest.js 控制器中使用类验证器来验证正文有效负载。我的currency.dto.ts文件是这样的:

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"
}]
}
4

2 回答 2

65

尝试使用以下命令指定嵌套类型@Type

import { Type } from 'class-transformer';

export class CurrencyDTO {
  @ValidateNested({ each: true })
  @Type(() => Data)
  data: Data[];
}

对于要验证的嵌套类型,它需要是一个类的实例,而不仅仅是一个普通的数据对象。使用@Type装饰器,您可以告诉 class-transformerplainToClassVaildationPipe.

如果您使用的是内置的,ValidationPipe请确保您已设置选项transform: true

于 2018-12-08T17:23:37.303 回答
0

至少在我的情况下,接受的答案需要更多信息。data照原样,如果请求中不存在密钥,验证将不会运行。要获得完整验证,请尝试:

@IsDefined()
@IsNotEmptyObject()
@ValidateNested()
@Type(() => CreateOrganizationDto)
@ApiProperty()
organization: CreateOrganizationDto;
于 2021-11-25T06:49:45.853 回答