Skip to content

Commit ee8e6d7

Browse files
committed
refactor: generateExample with zod union handler
1 parent f538ca3 commit ee8e6d7

File tree

2 files changed

+22
-2
lines changed

2 files changed

+22
-2
lines changed

src/utils/generateExample.test.ts

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import { describe, expect, it } from "@jest/globals";
2-
import z from "zod";
2+
import z, { type ZodType } from "zod";
33
import generateExample from "./generateExample";
44

55
describe("generateExample", () => {
@@ -104,6 +104,14 @@ describe("generateExample", () => {
104104
it("should generate an example from a zod array", () => {
105105
expect(generateExample(z.string().array(), true)).toStrictEqual(["example string"]);
106106
expect(generateExample(z.number().array(), true)).toStrictEqual([1]);
107+
expect(generateExample(z.array(z.union([z.string(), z.number()])), true)).toStrictEqual(["example string", 1]);
108+
});
109+
110+
it("should generate an example from a zod union", () => {
111+
const schema = z.union([z.string(), z.number()]);
112+
expect(generateExample(schema, true)).toBe("example string");
113+
const emptyUnion = z.union([] as unknown as [ZodType, ZodType]);
114+
expect(generateExample(emptyUnion, true)).toBe(undefined);
107115
});
108116

109117
it("should throw an error from an unknown zod schema", () => {

src/utils/generateExample.ts

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { ZodArray, ZodBigInt, ZodBoolean, ZodEnum, ZodNull, ZodNullable, ZodNumber, ZodObject, ZodOptional, ZodString, type ZodType, type ZodTypeDef, ZodUndefined } from "zod";
1+
import { ZodArray, ZodBigInt, ZodBoolean, ZodEnum, ZodNull, ZodNullable, ZodNumber, ZodObject, ZodOptional, ZodString, type ZodType, type ZodTypeDef, ZodUndefined, ZodUnion } from "zod";
22

33
export default function generateExample<I, O>(
44
schema: ZodType<O, ZodTypeDef, I>,
@@ -100,7 +100,19 @@ export default function generateExample<I, O>(
100100
return "example string" as unknown as O;
101101
}
102102
if (schema instanceof ZodArray) {
103+
if (schema._def.type instanceof ZodUnion) {
104+
const options = schema._def.type.options as ZodType[];
105+
return options.map(option => generateExample(option, ignoreOptionals)) as unknown as O;
106+
}
103107
return [generateExample(schema._def.type, ignoreOptionals)] as unknown as O;
104108
}
109+
if (schema instanceof ZodUnion) {
110+
const options = schema.options as ZodType[];
111+
const firstItem = options[0];
112+
if (firstItem) {
113+
return generateExample(firstItem, ignoreOptionals);
114+
}
115+
return undefined as unknown as O;
116+
}
105117
throw new Error("Unknown zod schema");
106118
}

0 commit comments

Comments
 (0)