mirror of
https://github.com/bigcapitalhq/bigcapital.git
synced 2026-02-14 20:00:33 +00:00
33 lines
905 B
TypeScript
33 lines
905 B
TypeScript
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) {
|
|
if (!metatype || !this.toValidate(metatype)) {
|
|
return value;
|
|
}
|
|
const object = plainToInstance(metatype, value);
|
|
const errors = await validate(object, {
|
|
// Strip validated object of any properties that do not have any decorators.
|
|
whitelist: true,
|
|
});
|
|
|
|
if (errors.length > 0) {
|
|
throw new BadRequestException(errors);
|
|
}
|
|
return object;
|
|
}
|
|
|
|
private toValidate(metatype: Function): boolean {
|
|
const types: Function[] = [String, Boolean, Number, Array, Object];
|
|
return !types.includes(metatype);
|
|
}
|
|
}
|