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:
Mathis H (Avnyr) 2024-07-09 16:02:17 +02:00
parent cac7d4cfd3
commit 763217dfdf
Signed by: Mathis
GPG Key ID: DD9E0666A747D126
2 changed files with 30 additions and 0 deletions

View 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
View 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;
}
}