Skip to content

Commit f538ca3

Browse files
committed
refactor: generateExample with zod array handler
1 parent 67ba032 commit f538ca3

File tree

2 files changed

+9
-1
lines changed

2 files changed

+9
-1
lines changed

src/utils/generateExample.test.ts

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -101,6 +101,11 @@ describe("generateExample", () => {
101101
expect(generateExample(schema, true)).toBe(undefined);
102102
});
103103

104+
it("should generate an example from a zod array", () => {
105+
expect(generateExample(z.string().array(), true)).toStrictEqual(["example string"]);
106+
expect(generateExample(z.number().array(), true)).toStrictEqual([1]);
107+
});
108+
104109
it("should throw an error from an unknown zod schema", () => {
105110
const schema = z.unknown();
106111
expect(() => generateExample(schema, false)).toThrow("Unknown zod schema");

src/utils/generateExample.ts

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { 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 } from "zod";
22

33
export default function generateExample<I, O>(
44
schema: ZodType<O, ZodTypeDef, I>,
@@ -99,5 +99,8 @@ export default function generateExample<I, O>(
9999
}
100100
return "example string" as unknown as O;
101101
}
102+
if (schema instanceof ZodArray) {
103+
return [generateExample(schema._def.type, ignoreOptionals)] as unknown as O;
104+
}
102105
throw new Error("Unknown zod schema");
103106
}

0 commit comments

Comments
 (0)