-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathIsValid.ts
32 lines (30 loc) · 1.11 KB
/
IsValid.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
import { ArgumentMetadata, BadRequestException, Injectable, PipeTransform } from '@nestjs/common';
import { validate } from 'class-validator';
import { plainToClass } from 'class-transformer';
@Injectable()
export class IsValid implements PipeTransform<any> {
async transform(value, metadata: ArgumentMetadata) {
const { metatype } = metadata;
if (!metatype || !this.toValidate(metatype)) {
return value;
}
const object = plainToClass(metatype, value);
const errors = await validate(object);
if (errors.length > 0) {
const constraints = errors[0].constraints;
let message = 'Validation failed';
for (const key in constraints) {
if (constraints[key]) {
message = constraints[key];
break;
}
}
throw new BadRequestException(message);
}
return value;
}
private toValidate(metatype): boolean {
const types = [String, Boolean, Number, Array, Object];
return !types.find(type => metatype === type);
}
}