import {
IsNumber,
IsString,
IsOptional,
IsNotEmpty,
IsArray,
} from 'class-validator';
export class DataDto {
@IsArray()
@ArrayNotEmpty()
@ValidateNested({ each: true })
@Type(() => UserDto)
readonly list: UserDto[]
}
export class UserDto {
@IsString()
@IsNotEmpty()
name: string
@IsNumber()
age?: number
}
import { validate } from 'class-validator';
import { plainToClass } from 'class-transformer';
import { Logger, PipeTransform, Injectable, ArgumentMetadata } from '@nestjs/common';
import { ValidationError } from '../errors/validation.error';
import { PARAMS_VALIDATION_ERROR } from '../constants/errorCode.constant';
@Injectable()
export class ValidationPipe implements PipeTransform<any> {
async transform(value, { metatype }: ArgumentMetadata) {
if (!metatype || !this.toValidate(metatype)) {
return value;
}
const object = plainToClass(metatype, value);
const errors = await validate(object, {forbidUnknownValues: true});
if (errors.length > 0) {
new Logger().warn(errors,'validationError');
const message = errors.map(error => Object.values(error.constraints).join(';')).join(';');
throw new ValidationError({code: PARAMS_VALIDATION_ERROR, message});
}
return value;
}
private toValidate(metatype): boolean {
const types = [String, Boolean, Number, Array, Object];
return !types.find(type => metatype === type);
}
}