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

Fix/recursive discriminated #304

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
33 changes: 20 additions & 13 deletions lib/src/openApiToZod.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,10 @@ import { match } from "ts-pattern";

import type { CodeMetaData, ConversionTypeContext } from "./CodeMeta";
import { CodeMeta } from "./CodeMeta";
import { inferRequiredSchema } from "./inferRequiredOnly";
import { isReferenceObject } from "./isReferenceObject";
import type { TemplateContext } from "./template-context";
import { escapeControlCharacters, isPrimitiveType, wrapWithQuotesIfNeeded } from "./utils";
import { inferRequiredSchema } from "./inferRequiredOnly";

type ConversionArgs = {
schema: SchemaObject | ReferenceObject;
Expand All @@ -19,6 +19,7 @@ type ConversionArgs = {
* @see https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#schemaObject
* @see https://github.com/colinhacks/zod
*/
let circularRef = "";
// eslint-disable-next-line sonarjs/cognitive-complexity
export function getZodSchema({ schema: $schema, ctx, meta: inheritedMeta, options }: ConversionArgs): CodeMeta {
if (!$schema) {
Expand All @@ -43,6 +44,8 @@ export function getZodSchema({ schema: $schema, ctx, meta: inheritedMeta, option

// circular(=recursive) reference
if (refsPath.length > 1 && refsPath.includes(schemaName)) {
circularRef = code.ref!;

return code.assign(ctx.zodSchemaByName[code.ref!]!);
}

Expand Down Expand Up @@ -93,10 +96,17 @@ export function getZodSchema({ schema: $schema, ctx, meta: inheritedMeta, option
if (schema.discriminator && !hasMultipleAllOf) {
const propertyName = schema.discriminator.propertyName;

const discriminatedUnionOptions = schema.oneOf.map((prop) =>
getZodSchema({ schema: prop, ctx, meta, options })
);
const isCircularDiscriminatedUnion = discriminatedUnionOptions.some((t) => t.ref === circularRef);

if (isCircularDiscriminatedUnion) {
return code.assign(`z.union([${discriminatedUnionOptions.join(", ")}])`);
}

return code.assign(`
z.discriminatedUnion("${propertyName}", [${schema.oneOf
.map((prop) => getZodSchema({ schema: prop, ctx, meta, options }))
.join(", ")}])
z.discriminatedUnion("${propertyName}", [${discriminatedUnionOptions.join(", ")}])
`);
}

Expand Down Expand Up @@ -138,6 +148,7 @@ export function getZodSchema({ schema: $schema, ctx, meta: inheritedMeta, option
const type = getZodSchema({ schema: schema.allOf[0]!, ctx, meta, options });
return code.assign(type.toString());
}

const { patchRequiredSchemaInLoop, noRequiredOnlyAllof, composedRequiredSchema } = inferRequiredSchema(schema);

const types = noRequiredOnlyAllof.map((prop) => {
Expand Down Expand Up @@ -213,15 +224,11 @@ export function getZodSchema({ schema: $schema, ctx, meta: inheritedMeta, option
if (schemaType === "array") {
if (schema.items) {
return code.assign(
`z.array(${
getZodSchema({ schema: schema.items, ctx, meta, options }).toString()
}${
getZodChain({
schema: schema.items as SchemaObject,
meta: { ...meta, isRequired: true },
options,
})
})${readonly}`
`z.array(${getZodSchema({ schema: schema.items, ctx, meta, options }).toString()}${getZodChain({
schema: schema.items as SchemaObject,
meta: { ...meta, isRequired: true },
options,
})})${readonly}`
);
}

Expand Down
2 changes: 1 addition & 1 deletion lib/src/template-context.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { sortBy, sortListFromRefArray, sortObjKeysFromArray } from "pastable/ser
import { ts } from "tanu";
import { match } from "ts-pattern";

import type { CodeMetaData } from "./CodeMeta";
import { getOpenApiDependencyGraph } from "./getOpenApiDependencyGraph";
import type { EndpointDefinitionWithRefs } from "./getZodiosEndpointDefinitionList";
import { getZodiosEndpointDefinitionList } from "./getZodiosEndpointDefinitionList";
Expand All @@ -11,7 +12,6 @@ import { getTypescriptFromOpenApi } from "./openApiToTypescript";
import { getZodSchema } from "./openApiToZod";
import { topologicalSort } from "./topologicalSort";
import { asComponentSchema, normalizeString } from "./utils";
import type { CodeMetaData } from "./CodeMeta";

const file = ts.createSourceFile("", "", ts.ScriptTarget.ESNext, true);
const printer = ts.createPrinter({ newLine: ts.NewLineKind.LineFeed });
Expand Down