2025-09-19 16:34:10 +09:00
|
|
|
/**
|
|
|
|
|
* Simple Zod Validation Pipe for NestJS
|
|
|
|
|
* Just uses Zod as-is with clean error formatting
|
|
|
|
|
*/
|
|
|
|
|
|
2025-09-24 18:00:49 +09:00
|
|
|
import type { PipeTransform, ArgumentMetadata } from "@nestjs/common";
|
|
|
|
|
import { Injectable, BadRequestException } from "@nestjs/common";
|
2025-09-20 13:33:47 +09:00
|
|
|
import type { ZodSchema } from "zod";
|
|
|
|
|
import { ZodError } from "zod";
|
2025-09-19 16:34:10 +09:00
|
|
|
|
|
|
|
|
@Injectable()
|
|
|
|
|
export class ZodValidationPipe implements PipeTransform {
|
2025-09-20 13:33:47 +09:00
|
|
|
constructor(private readonly schema: ZodSchema) {}
|
2025-09-19 16:34:10 +09:00
|
|
|
|
2025-09-20 13:33:47 +09:00
|
|
|
transform(value: unknown, _metadata: ArgumentMetadata): unknown {
|
2025-09-19 16:34:10 +09:00
|
|
|
try {
|
|
|
|
|
return this.schema.parse(value);
|
|
|
|
|
} catch (error) {
|
|
|
|
|
if (error instanceof ZodError) {
|
|
|
|
|
const errors = error.issues.map(issue => ({
|
2025-09-20 13:33:47 +09:00
|
|
|
field: issue.path.join(".") || "root",
|
2025-09-19 16:34:10 +09:00
|
|
|
message: issue.message,
|
2025-09-20 13:33:47 +09:00
|
|
|
code: issue.code,
|
2025-09-19 16:34:10 +09:00
|
|
|
}));
|
2025-09-20 13:33:47 +09:00
|
|
|
|
2025-09-19 16:34:10 +09:00
|
|
|
throw new BadRequestException({
|
2025-09-20 13:33:47 +09:00
|
|
|
message: "Validation failed",
|
2025-09-19 16:34:10 +09:00
|
|
|
errors,
|
2025-09-20 13:33:47 +09:00
|
|
|
statusCode: 400,
|
2025-09-19 16:34:10 +09:00
|
|
|
});
|
|
|
|
|
}
|
2025-09-20 13:33:47 +09:00
|
|
|
|
|
|
|
|
const message = error instanceof Error ? error.message : "Validation failed";
|
|
|
|
|
throw new BadRequestException(message);
|
2025-09-19 16:34:10 +09:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* 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);
|