You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

40 lines
1.1 KiB
TypeScript

import {
PipeTransform,
Injectable,
ArgumentMetadata,
BadRequestException,
} from '@nestjs/common';
import { validate } from 'class-validator';
import { plainToClass } from 'class-transformer';
@Injectable()
export class ValidationPipe implements PipeTransform<any> {
async transform(value, { type, metatype }: ArgumentMetadata) {
console.log(value)
if (type === 'query' && value.skip && value.take) {
value = {
...value,
skip: ((parseInt(value.skip, 10) || 1) - 1) * (parseInt(value.take, 10) || 10),
take: parseInt(value.take, 10) || 10,
};
}
if (!metatype || !this.toValidate(metatype)) {
return value;
}
console.log(value)
const object = plainToClass(metatype, value);
const errors = await validate(object);
console.log(errors)
if (errors.length > 0) {
throw new BadRequestException(errors);
// throw new BadRequestException('Validation failed');
}
return value;
}
private toValidate(metatype): boolean {
const types = [String, Boolean, Number, Array, Object];
return !types.find(type => metatype === type);
}
}