Skip to content

Commit af16fa8

Browse files
committed
fix(zod-openapi): do not mutate original schema with extendApi
1 parent cbea74d commit af16fa8

File tree

2 files changed

+17
-2
lines changed

2 files changed

+17
-2
lines changed

packages/zod-openapi/src/lib/zod-openapi.spec.ts

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -961,4 +961,13 @@ describe('zodOpenapi', () => {
961961
maximum: 10,
962962
} satisfies SchemaObject);
963963
});
964+
965+
it('should not mutate the original schema', () => {
966+
const s1 = extendApi(z.string(), { description: 's1' });
967+
const s2 = extendApi(s1, { description: 's2' });
968+
const apiSchema1 = generateSchema(s1);
969+
const apiSchema2 = generateSchema(s2);
970+
expect(apiSchema1.description).toEqual('s1');
971+
expect(apiSchema2.description).toEqual('s2');
972+
});
964973
});

packages/zod-openapi/src/lib/zod-openapi.ts

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -23,8 +23,14 @@ export function extendApi<T extends OpenApiZodAny>(
2323
schema: T,
2424
schemaObject: AnatineSchemaObject = {}
2525
): T {
26-
schema.metaOpenApi = Object.assign(schema.metaOpenApi || {}, schemaObject);
27-
return schema;
26+
const This = (schema as any).constructor;
27+
const newSchema = new This(schema._def);
28+
newSchema.metaOpenApi = Object.assign(
29+
{},
30+
schema.metaOpenApi || {},
31+
schemaObject
32+
);
33+
return newSchema;
2834
}
2935

3036
function iterateZodObject({

0 commit comments

Comments
 (0)