返回 AiToEarn
zod-dto.util.ts
根目录 / project / aitoearn-backend / libs / common / src / utils / zod-dto.util.ts
1 import { z, ZodType } from 'zod'
2 import { ZodErrorWithInput } from '../exceptions/zod-error-with-input.exception'
3
4 export interface ZodDto<
5 TOutput = unknown,
6 TInput = TOutput,
7 > {
8 new (): TOutput
9 isZodDto: true
10 schema: ZodType<TOutput, TInput>
11 create: (input: TInput) => TOutput
12 }
13
14 export function createZodDto<
15 TOutput = unknown,
16 TInput = TOutput,
17 >(schema: ZodType<TOutput, TInput>, id?: string) {
18 if (id)
19 z.globalRegistry.add(schema, { id })
20
21 class AugmentedZodDto {
22 public static isZodDto = true
23 public static schema = schema
24
25 public static create(input: TInput) {
26 const result = this.schema.safeParse(input)
27 if (result.success)
28 return result.data
29 throw new ZodErrorWithInput(result.error.issues, input)
30 }
31 }
32
33 return AugmentedZodDto as unknown as ZodDto<TOutput, TInput>
34 }
35
36 export function isZodDto(metatype: unknown): metatype is ZodDto {
37 return typeof metatype === 'function'
38 && 'isZodDto' in metatype
39 && metatype.isZodDto === true
40 }
41
41 lines TYPESCRIPT