Skip to content

Commit

Permalink
🔀 Merge pull request #78 from StefanTerdell/fix-#77
Browse files Browse the repository at this point in the history
Fix #77
  • Loading branch information
StefanTerdell authored Jun 27, 2023
2 parents a1467f5 + f4e938b commit 3922e79
Show file tree
Hide file tree
Showing 2 changed files with 66 additions and 13 deletions.
24 changes: 11 additions & 13 deletions src/parsers/nullable.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,21 +41,19 @@ export function parseNullableDef(
};
}

const type = parseDef(def.innerType._def, {
if (refs.target === "openApi3") {
const base = parseDef(def.innerType._def, {
...refs,
currentPath: [...refs.currentPath],
});

return base && ({ ...base, nullable: true } as any);
}

const base = parseDef(def.innerType._def, {
...refs,
currentPath: [...refs.currentPath, "anyOf", "0"],
});

return type
? refs.target === "openApi3"
? ({ ...type, nullable: true } as any)
: {
anyOf: [
type,
{
type: "null",
},
],
}
: undefined;
return base && { anyOf: [base, { type: "null" }] };
}
55 changes: 55 additions & 0 deletions test/openApiMode.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,4 +48,59 @@ describe("Open API target", () => {

expect(swaggerSchema).toStrictEqual(expectedSchema);
});

it("should properly reference nullable schemas", () => {
const legalReasonSchema = z
.object({
reason: z.enum(["FOO", "BAR"]),
})
.strict();

const identityRequestSchema = z
.object({
alias: z
.object({
legalReason: legalReasonSchema.nullish(), // reused here
})
.strict(),
requiredLegalReasonTypes: z
.array(legalReasonSchema.shape.reason)
.nullish(), // reused here
})
.strict();

const result = zodToJsonSchema(identityRequestSchema, {
target: "openApi3",
});

const expected = {
type: "object",
properties: {
alias: {
type: "object",
properties: {
legalReason: {
type: "object",
properties: { reason: { type: "string", enum: ["FOO", "BAR"] } },
required: ["reason"],
additionalProperties: false,
nullable: true,
},
},
additionalProperties: false,
},
requiredLegalReasonTypes: {
type: "array",
items: {
$ref: "#/properties/alias/properties/legalReason/properties/reason",
},
nullable: true,
},
},
required: ["alias"],
additionalProperties: false,
};

expect(result).toStrictEqual(expected);
});
});

0 comments on commit 3922e79

Please sign in to comment.