forked from Nova-reward/Nova-Rewards
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathzod-validation.pipe.ts
More file actions
45 lines (41 loc) · 1.21 KB
/
Copy pathzod-validation.pipe.ts
File metadata and controls
45 lines (41 loc) · 1.21 KB
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
40
41
42
43
44
45
import { PipeTransform, Injectable, BadRequestException, ArgumentMetadata } from '@nestjs/common';
import { ZodSchema, ZodError } from 'zod';
import { fromZodError } from 'zod-validation-error';
@Injectable()
export class ZodValidationPipe implements PipeTransform {
constructor(
private schema: ZodSchema,
private options?: {
stripUnknown?: boolean;
type?: 'body' | 'query' | 'param';
}
) {}
transform(value: unknown, metadata: ArgumentMetadata) {
if (this.options?.type && metadata.type !== this.options.type) {
return value;
}
try {
const parsed = this.schema.parse(value);
if (this.options?.stripUnknown) {
return parsed;
}
return parsed;
} catch (error) {
if (error instanceof ZodError) {
const formattedError = fromZodError(error, {
prefix: 'Validation failed',
includePath: true,
});
throw new BadRequestException({
error: 'Validation failed',
details: formattedError.details.map(detail => ({
field: detail.path.join('.'),
message: detail.message,
})),
statusCode: 400,
});
}
throw error;
}
}
}