think/packages/server/src/pipes/validation.pipe.ts

26 lines
888 B
TypeScript
Raw Normal View History

2022-05-16 09:23:59 +00:00
import { ArgumentMetadata, BadRequestException, Injectable, PipeTransform } from '@nestjs/common';
2022-02-20 11:51:55 +00:00
import { plainToClass } from 'class-transformer';
2022-05-16 09:23:59 +00:00
import { validate } from 'class-validator';
2022-02-20 11:51:55 +00:00
@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);
}
}