| 1 | import type { ZodType } from 'zod' |
| 2 | import type { ZodExceptionCreator } from '../exceptions' |
| 3 | import type { ZodDto } from './zod-dto.util' |
| 4 | import { createZodValidationException } from '../exceptions' |
| 5 | import { isZodDto } from './zod-dto.util' |
| 6 | |
| 7 | export function zodValidate< |
| 8 | TOutput = unknown, |
| 9 | TInput = TOutput, |
| 10 | >( |
| 11 | value: TInput, |
| 12 | schemaOrDto: ZodType<TOutput, TInput> | ZodDto<TOutput, TInput>, |
| 13 | createValidationException: ZodExceptionCreator = createZodValidationException, |
| 14 | ): TOutput { |
| 15 | const schema: any = isZodDto(schemaOrDto) ? schemaOrDto.schema : schemaOrDto |
| 16 | |
| 17 | const result = schema.safeParse(value) |
| 18 | |
| 19 | if (!result.success) { |
| 20 | throw createValidationException(result.error) |
| 21 | } |
| 22 | |
| 23 | return result.data as TOutput |
| 24 | } |
| 25 |