返回 AiToEarn
zod-openapi.util.ts
根目录 / project / aitoearn-backend / libs / common / src / utils / zod-openapi.util.ts
1 import type { Type } from '@nestjs/common'
2 import type { SchemaObject } from '@nestjs/swagger/dist/interfaces/open-api-spec.interface'
3 import { SchemaObjectFactory } from '@nestjs/swagger/dist/services/schema-object-factory'
4 import { z } from 'zod'
5 import { isZodDto } from './zod-dto.util'
6
7 export const zodToJsonSchemaOptions: Parameters<typeof z.toJSONSchema>[1] = {
8 uri: id => `#/components/schemas/${id}`,
9 target: 'draft-7',
10 unrepresentable: 'any',
11 cycles: 'ref',
12 override: (ctx) => {
13 const _zod = ctx.zodSchema._zod
14 const def = _zod.def
15 if (def.type === 'date') {
16 ctx.jsonSchema.type = 'string'
17 ctx.jsonSchema.format = 'date-time'
18 }
19 },
20 }
21
22 export function patchNestJsSwagger() {
23 if ('__patchedWithLoveByNestjsZod' in SchemaObjectFactory.prototype)
24 return
25 const defaultExplore = SchemaObjectFactory.prototype.exploreModelSchema
26
27 SchemaObjectFactory.prototype.exploreModelSchema = function (
28 this: SchemaObjectFactory | undefined,
29 type,
30 schemas,
31 schemaRefsStack,
32 ) {
33 if (this && this['isLazyTypeFunc'](type)) {
34 const factory = type as () => Type<unknown>
35 type = factory()
36 }
37
38 if (!isZodDto(type)) {
39 return defaultExplore.call(this, type, schemas, schemaRefsStack)
40 }
41
42 schemas[type.name] = z.toJSONSchema(type.schema, zodToJsonSchemaOptions) as SchemaObject
43 return type.name
44 }
45 // @ts-expect-error set __patchedWithLoveByNestjsZod to true
46 SchemaObjectFactory.prototype.__patchedWithLoveByNestjsZod = true
47 }
48
48 lines TYPESCRIPT