Skip to content

Commit 2ae51ff

Browse files
authored
Merge pull request #4 from DopplerHQ/mike/parser-enum-fix
Fix Zod validation for non-string enums in OpenAPI parser
2 parents 182c251 + 47f3724 commit 2ae51ff

1 file changed

Lines changed: 22 additions & 3 deletions

File tree

src/parser.ts

Lines changed: 22 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -241,10 +241,29 @@ export class OpenAPIParser {
241241

242242
private convertSchemaToZod(schema: SchemaObject): z.ZodSchema<any> {
243243
if (schema.enum) {
244-
const cleanedEnum = schema.enum.map((val: any) =>
245-
typeof val === "string" ? val.replace(/^"|"$/g, "") : val,
244+
const allStrings = schema.enum.every(
245+
(val: any) => typeof val === "string",
246+
);
247+
if (allStrings) {
248+
const cleanedEnum = schema.enum.map((val: string) =>
249+
val.replace(/^"|"$/g, ""),
250+
);
251+
return z.enum(cleanedEnum as [string, ...string[]]);
252+
}
253+
// Non-string enums use z.union of literals
254+
if (schema.enum.length === 0) {
255+
return z.never();
256+
}
257+
if (schema.enum.length === 1) {
258+
return z.literal(schema.enum[0]);
259+
}
260+
return z.union(
261+
schema.enum.map((val: any) => z.literal(val)) as [
262+
z.ZodLiteral<any>,
263+
z.ZodLiteral<any>,
264+
...z.ZodLiteral<any>[],
265+
],
246266
);
247-
return z.enum(cleanedEnum as [string, ...string[]]);
248267
}
249268

250269
switch (schema.type) {

0 commit comments

Comments
 (0)