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