@@ -0,0 +1,17 @@
|
||||
import { BadRequestException, PipeTransform } from '@nestjs/common';
|
||||
import { z } from 'zod';
|
||||
|
||||
/** Validates and converts a body or query with a schema from @kooltap/shared: `@Body(zod(schema))`. */
|
||||
export class ZodPipe<S extends z.ZodType> implements PipeTransform<unknown, z.output<S>> {
|
||||
constructor(private readonly schema: S) {}
|
||||
|
||||
transform(value: unknown): z.output<S> {
|
||||
const result = this.schema.safeParse(value);
|
||||
if (!result.success) {
|
||||
throw new BadRequestException({ code: 'validation_error', message: z.prettifyError(result.error) });
|
||||
}
|
||||
return result.data;
|
||||
}
|
||||
}
|
||||
|
||||
export const zod = <S extends z.ZodType>(schema: S) => new ZodPipe(schema);
|
||||
Reference in New Issue
Block a user