| 1 | import type { ArgumentMetadata, PipeTransform } from '@nestjs/common' |
| 2 | import type { ZodType } from 'zod' |
| 3 | import type { ZodDto } from '../utils' |
| 4 | import { ValidationPipe } from '@nestjs/common' |
| 5 | import { isZodDto, zodValidate } from '../utils' |
| 6 | |
| 7 | export class ZodValidationPipe extends ValidationPipe implements PipeTransform { |
| 8 | constructor(private schemaOrDto?: ZodType | ZodDto) { |
| 9 | super({ |
| 10 | transform: true, |
| 11 | whitelist: true, |
| 12 | transformOptions: { |
| 13 | excludeExtraneousValues: true, |
| 14 | }, |
| 15 | }) |
| 16 | } |
| 17 | |
| 18 | public override transform(value: unknown, metadata: ArgumentMetadata): Promise<unknown> { |
| 19 | if (this.schemaOrDto) { |
| 20 | return Promise.resolve(zodValidate(value, this.schemaOrDto)) |
| 21 | } |
| 22 | |
| 23 | const { metatype } = metadata |
| 24 | |
| 25 | if (!isZodDto(metatype)) { |
| 26 | return super.transform(value, metadata) |
| 27 | } |
| 28 | |
| 29 | return Promise.resolve(zodValidate(value, metatype.schema)) |
| 30 | } |
| 31 | } |
| 32 |