Skip to content

Commit efd2902

Browse files
committed
fix: Date cannot be represented in JSON Schema
1 parent 2c64f2f commit efd2902

File tree

1 file changed

+25
-2
lines changed

1 file changed

+25
-2
lines changed

src/core/zod-to-openapi.ts

Lines changed: 25 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,29 @@
1-
import { type ZodType, z } from "zod";
1+
import { type ZodObject, type ZodType, z } from "zod";
22
import type { SchemaObject } from "@omer-x/openapi-types/schema";
33

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+
427
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;
629
}

0 commit comments

Comments
 (0)