46 lines
1.2 KiB
TypeScript
46 lines
1.2 KiB
TypeScript
/**
|
|
* Simple Zod Validation Pipe for NestJS
|
|
* Just uses Zod as-is with clean error formatting
|
|
*/
|
|
|
|
import { PipeTransform, Injectable, BadRequestException } from '@nestjs/common';
|
|
import type { ArgumentMetadata } from '@nestjs/common';
|
|
import type { ZodSchema } from 'zod';
|
|
import { ZodError } from 'zod';
|
|
|
|
@Injectable()
|
|
export class ZodValidationPipe implements PipeTransform {
|
|
constructor(private schema: ZodSchema) {}
|
|
|
|
transform(value: unknown, metadata: ArgumentMetadata) {
|
|
try {
|
|
return this.schema.parse(value);
|
|
} catch (error) {
|
|
if (error instanceof ZodError) {
|
|
const errors = error.issues.map(issue => ({
|
|
field: issue.path.join('.') || 'root',
|
|
message: issue.message,
|
|
code: issue.code
|
|
}));
|
|
|
|
throw new BadRequestException({
|
|
message: 'Validation failed',
|
|
errors,
|
|
statusCode: 400
|
|
});
|
|
}
|
|
throw new BadRequestException('Validation failed');
|
|
}
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Factory function to create Zod pipe (main export)
|
|
*/
|
|
export const ZodPipe = (schema: ZodSchema) => new ZodValidationPipe(schema);
|
|
|
|
/**
|
|
* Alternative factory function
|
|
*/
|
|
export const createZodPipe = (schema: ZodSchema) => new ZodValidationPipe(schema);
|