2025-01-06 08:45:23 +08:00
|
|
|
import { PipeTransform, BadRequestException } from '@nestjs/common';
|
|
|
|
import { ZodSchema } from 'zod';
|
|
|
|
|
|
|
|
export class ZodValidationPipe implements PipeTransform {
|
2025-03-31 20:44:33 +08:00
|
|
|
constructor(private schema: ZodSchema) {}
|
2025-01-06 08:45:23 +08:00
|
|
|
|
2025-03-31 20:44:33 +08:00
|
|
|
transform(value: unknown) {
|
|
|
|
try {
|
|
|
|
const result = this.schema.parse(value);
|
|
|
|
return result;
|
|
|
|
} catch (error: any) {
|
|
|
|
throw new BadRequestException('Validation failed', {
|
|
|
|
cause: error,
|
|
|
|
description: error.errors,
|
|
|
|
});
|
2025-01-06 08:45:23 +08:00
|
|
|
}
|
2025-03-31 20:44:33 +08:00
|
|
|
}
|
|
|
|
}
|