const err = new Error('test123');
// @ts-ignore
err.statusCode = 403;
import { PipeTransform, Injectable, ArgumentMetadata, BadRequestException } from '@nestjs/common';
import { validate } from 'class-validator';
import { plainToInstance } from 'class-transformer';
@Injectable()
export class ValidationPipe implements PipeTransform<any> {
async transform(value: any, { metatype }: ArgumentMetadata) {
console.log('!!!!!', typeof value);
console.log('!!!!!', typeof metatype);
if (!metatype || !this.toValidate(metatype)) {
return value;
}
// metatype是dto类, value是body里的值
const object = plainToInstance(metatype, value);
const errors = await validate(object);
if (errors.length > 0) {
throw new BadRequestException('Validation failed' + errors.toString());
}
return value;
}
private toValidate(metatype: Function): boolean {
const types: Function[] = [String, Boolean, Number, Array, Object];
return !types.includes(metatype);
}
}
上面这个ValidatorPipe其实没必要写,因为nest原生的就提供。另外,可以app.useGlobalPipe去设置,也可以在controller,方法,或者参数上去设置