feat(pipes): add zod filter and zod pipe
This commit introduces two new files: zod.pipe.filter.ts and zod.pipe.ts. The `ZodFilter` catches ZodErrors and defines the HTTP response json format. The `ZodPipe` validates incoming data against a predefined schema.
This commit is contained in:
parent
cac7d4cfd3
commit
763217dfdf
17
src/pipes/zod.pipe.filter.ts
Normal file
17
src/pipes/zod.pipe.filter.ts
Normal file
@ -0,0 +1,17 @@
|
|||||||
|
import { ArgumentsHost, Catch, ExceptionFilter, HttpStatus } from "@nestjs/common";
|
||||||
|
import { ZodError } from "zod";
|
||||||
|
|
||||||
|
|
||||||
|
@Catch(ZodError)
|
||||||
|
export class ZodFilter<T extends ZodError> implements ExceptionFilter {
|
||||||
|
catch(exception: T, host: ArgumentsHost) {
|
||||||
|
const ctx = host.switchToHttp();
|
||||||
|
const response = ctx.getResponse();
|
||||||
|
const status = HttpStatus.BAD_REQUEST;
|
||||||
|
response.status(status).json({
|
||||||
|
errors: exception.errors,
|
||||||
|
message: exception.message,
|
||||||
|
statusCode: status,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
13
src/pipes/zod.pipe.ts
Normal file
13
src/pipes/zod.pipe.ts
Normal file
@ -0,0 +1,13 @@
|
|||||||
|
import { ArgumentMetadata, Injectable, PipeTransform } from "@nestjs/common";
|
||||||
|
import { z } from "zod";
|
||||||
|
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class ZodPipe implements PipeTransform {
|
||||||
|
constructor(private readonly schema: z.ZodObject<any>) {}
|
||||||
|
|
||||||
|
transform(value: any, metadata: ArgumentMetadata) {
|
||||||
|
this.schema.parse(value);
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
}
|
Loading…
x
Reference in New Issue
Block a user