|
1 | | -import { type ZodType, z } from "zod"; |
| 1 | +import { type ZodObject, type ZodType, z } from "zod"; |
2 | 2 | import type { SchemaObject } from "@omer-x/openapi-types/schema"; |
3 | 3 |
|
| 4 | +function fixSchema(schema: ZodType<unknown>): ZodType<unknown> { |
| 5 | + if ("unwrap" in schema && typeof schema.unwrap === "function") { |
| 6 | + switch (schema._zod.def.type) { |
| 7 | + case "nullable": return fixSchema(schema.unwrap()).nullable(); |
| 8 | + case "optional": return fixSchema(schema.unwrap()).optional(); |
| 9 | + case "readonly": return fixSchema(schema.unwrap()).readonly(); |
| 10 | + case "array": return fixSchema(schema.unwrap()).array(); |
| 11 | + default: throw new Error(`${schema._zod.def.type} type is not covered in fixSchema (@omer-x/next-openapi-json-generator")`); |
| 12 | + } |
| 13 | + } |
| 14 | + if (schema._zod.def.type === "date") { |
| 15 | + return z.iso.datetime(); |
| 16 | + } |
| 17 | + if (schema._zod.def.type === "object") { |
| 18 | + const { shape } = schema as ZodObject; |
| 19 | + const entries = Object.entries(shape); |
| 20 | + const alteredEntries = entries.map(([propName, prop]) => [propName, fixSchema(prop)]); |
| 21 | + const newShape = Object.fromEntries(alteredEntries); |
| 22 | + return z.object(newShape); |
| 23 | + } |
| 24 | + return schema; |
| 25 | +} |
| 26 | + |
4 | 27 | export default function convertToOpenAPI(schema: ZodType<unknown>, isArray: boolean) { |
5 | | - return z.toJSONSchema(isArray ? schema.array() : schema) as SchemaObject; |
| 28 | + return z.toJSONSchema(fixSchema(isArray ? schema.array() : schema)) as SchemaObject; |
6 | 29 | } |
0 commit comments