-
Notifications
You must be signed in to change notification settings - Fork 2
/
dto-validation-pipe.ts
39 lines (32 loc) · 976 Bytes
/
dto-validation-pipe.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
33
34
35
36
37
38
39
import {
ArgumentMetadata,
BadRequestException,
Injectable,
PipeTransform,
} from '@nestjs/common';
import { DTObject, ParseError } from 'dto-classes';
@Injectable()
export class DTOValidationPipe implements PipeTransform {
async transform(value: any, metadata: ArgumentMetadata) {
let DTOClass: typeof DTObject = null;
if (metadata.metatype.prototype instanceof DTObject) {
DTOClass = metadata.metatype as any;
}
if (!DTOClass) {
return value;
}
try {
value = await DTOClass.parse(value);
} catch (e) {
if (e instanceof ParseError) {
throw new BadRequestException({
message: 'Validation failed.',
error: e.issues.map(x => {
return { message: x.message, path: x.path }
})
});
}
}
return value;
}
}