Skip to content
Closed
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
46 changes: 46 additions & 0 deletions packages/zod/src/v4/classic/tests/to-json-schema.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1535,6 +1535,52 @@ test("describe with id", () => {
`);
});

test("override with id", () => {
const jobId = z.string().meta({ id: "jobIdFoo" });

const a = z.z.toJSONSchema(
z.object({
current: jobId.describe("Current job"),
previous: jobId.describe("Previous job"),
}),
{
override(ctx) {
if (ctx.path.join("/") === "$defs/jobIdFoo") {
ctx.jsonSchema.id = "jobIdChanged";
}
},
}
);

expect(a).toMatchInlineSnapshot(`
{
"$defs": {
"jobIdFoo": {
"id": "jobIdChanged",
"type": "string",
},
},
"$schema": "https://json-schema.org/draft/2020-12/schema",
"additionalProperties": false,
"properties": {
"current": {
"$ref": "#/$defs/jobIdFoo",
"description": "Current job",
},
"previous": {
"$ref": "#/$defs/jobIdFoo",
"description": "Previous job",
},
},
"required": [
"current",
"previous",
],
"type": "object",
}
`);
});

test("overwrite id", () => {
const jobId = z.string().meta({ id: "aaa" });

Expand Down
8 changes: 8 additions & 0 deletions packages/zod/src/v4/core/to-json-schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -817,9 +817,17 @@ export class JSONSchemaGenerator {

// build defs object
const defs: JSONSchema.BaseSchema["$defs"] = params.external?.defs ?? {};

const rootKey = this.target === "draft-2020-12" ? "$defs" : "definitions";

for (const entry of this.seen.entries()) {
const seen = entry[1];
if (seen.def && seen.defId) {
this.override({
zodSchema: entry[0] as schemas.$ZodTypes,
jsonSchema: seen.def,
path: [rootKey, seen.defId],
});
defs[seen.defId] = seen.def;
}
}
Expand Down