mirror of https://github.com/fantasticit/think.git
31 lines
897 B
TypeScript
31 lines
897 B
TypeScript
|
import {
|
||
|
ArgumentMetadata,
|
||
|
Injectable,
|
||
|
PipeTransform,
|
||
|
BadRequestException,
|
||
|
} from '@nestjs/common';
|
||
|
import { validate } from 'class-validator';
|
||
|
import { plainToClass } from 'class-transformer';
|
||
|
|
||
|
@Injectable()
|
||
|
export class ValidationPipe implements PipeTransform {
|
||
|
async transform(value: any, { metatype }: ArgumentMetadata) {
|
||
|
if (!metatype || !this.toValidate(metatype)) {
|
||
|
return value;
|
||
|
}
|
||
|
const object = plainToClass(metatype, value);
|
||
|
const errors = await validate(object);
|
||
|
if (errors.length > 0) {
|
||
|
const msg = Object.values(errors[0].constraints)[0];
|
||
|
console.error(`Validation failed: ${msg}`);
|
||
|
throw new BadRequestException(`Validation failed: ${msg}`);
|
||
|
}
|
||
|
return value;
|
||
|
}
|
||
|
|
||
|
private toValidate(metatype: any): boolean {
|
||
|
const types: any[] = [String, Boolean, Number, Array, Object];
|
||
|
return !types.includes(metatype);
|
||
|
}
|
||
|
}
|