Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Zod chain for union types #312

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/bright-suits-allow.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"openapi-zod-client": minor
---

Add support for chained validation to composed types (oneOf, anyOf, allOf)
65 changes: 47 additions & 18 deletions lib/src/openApiToZod.ts
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,12 @@ export function getZodSchema({ schema: $schema, ctx, meta: inheritedMeta, option
if (schema.oneOf) {
if (schema.oneOf.length === 1) {
const type = getZodSchema({ schema: schema.oneOf[0]!, ctx, meta, options });
return code.assign(type.toString());
const chain = getZodChain({
schema: type.schema as SchemaObject,
meta: { ...meta, isRequired: true },
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm admittendly not entirely sure why isRequired: true is needed here and in the other places I added getZodChain calls. I tried excluding it at first, but it resulted in many test failures, and including it gave the results I was expecting.

options
});
return code.assign(`${type.toString()}${chain}`);
}

/* when there are multiple allOf we are unable to use a discriminatedUnion as this library adds an
Expand All @@ -101,32 +106,39 @@ export function getZodSchema({ schema: $schema, ctx, meta: inheritedMeta, option
}

return code.assign(
`z.union([${schema.oneOf.map((prop) => getZodSchema({ schema: prop, ctx, meta, options })).join(", ")}])`
`z.union([${schema.oneOf.map((prop) => {
const type = getZodSchema({ schema: prop, ctx, meta, options });
const chain = getZodChain({
schema: prop as SchemaObject,
meta: { ...meta, isRequired: true },
options
});
return `${type.toString()}${chain}`;
}).join(", ")}])`
);
}

// anyOf = oneOf but with 1 or more = `T extends oneOf ? T | T[] : never`
if (schema.anyOf) {
if (schema.anyOf.length === 1) {
const type = getZodSchema({ schema: schema.anyOf[0]!, ctx, meta, options });
return code.assign(type.toString());
const chain = getZodChain({
schema: type.schema as SchemaObject,
meta: { ...meta, isRequired: true },
options
});
return code.assign(`${type.toString()}${chain}`);
}

const types = schema.anyOf
.map((prop) => getZodSchema({ schema: prop, ctx, meta, options }))
.map((type) => {
let isObject = true;

if ("type" in type.schema) {
if (Array.isArray(type.schema.type)) {
isObject = false;
} else {
const schemaType = type.schema.type.toLowerCase() as NonNullable<typeof schema.type>;
isObject = !isPrimitiveType(schemaType);
}
}
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

isObject was unused, so this if/else to set its value was unneeded.


return type.toString();
const chain = getZodChain({
schema: type.schema as SchemaObject,
meta: { ...meta, isRequired: true },
options
});
return `${type.toString()}${chain}`;
})
.join(", ");

Expand All @@ -136,7 +148,12 @@ export function getZodSchema({ schema: $schema, ctx, meta: inheritedMeta, option
if (schema.allOf) {
if (schema.allOf.length === 1) {
const type = getZodSchema({ schema: schema.allOf[0]!, ctx, meta, options });
return code.assign(type.toString());
const chain = getZodChain({
schema: type.schema as SchemaObject,
meta: { ...meta, isRequired: true },
options
});
return code.assign(`${type.toString()}${chain}`);
}
const { patchRequiredSchemaInLoop, noRequiredOnlyAllof, composedRequiredSchema } = inferRequiredSchema(schema);

Expand All @@ -159,10 +176,22 @@ export function getZodSchema({ schema: $schema, ctx, meta: inheritedMeta, option
const first = types.at(0)!;
const rest = types
.slice(1)
.map((type) => `and(${type.toString()})`)
.map((type) => {
const chain = getZodChain({
schema: type.schema as SchemaObject,
meta: { ...meta, isRequired: true },
options,
});
return `and(${type.toString()}${chain})`;
})
.join(".");

return code.assign(`${first.toString()}.${rest}`);
const firstChain = getZodChain({
schema: first.schema as SchemaObject,
meta: { ...meta, isRequired: true },
options,
});
return code.assign(`${first.toString()}${firstChain}.${rest}`);
}

const schemaType = schema.type ? (schema.type.toLowerCase() as NonNullable<typeof schema.type>) : undefined;
Expand Down
Loading