Skip to content

Commit

Permalink
fix(zod-openapi): do not mutate original schema with extendApi
Browse files Browse the repository at this point in the history
  • Loading branch information
Ugzuzg committed Jan 18, 2024
1 parent 1cfb5ef commit 6684ca6
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 2 deletions.
8 changes: 8 additions & 0 deletions packages/zod-openapi/src/lib/zod-openapi.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1027,6 +1027,14 @@ describe('zodOpenapi', () => {
"type": "object",
}
`);
});

it('should not mutate the original schema', () => {
const s1 = extendApi(z.string(), { description: 's1' });
const s2 = extendApi(s1, { description: 's2' });
const apiSchema1 = generateSchema(s1);
const apiSchema2 = generateSchema(s2);
expect(apiSchema1.description).toEqual('s1');
expect(apiSchema2.description).toEqual('s2');
});
});
10 changes: 8 additions & 2 deletions packages/zod-openapi/src/lib/zod-openapi.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,14 @@ export function extendApi<T extends OpenApiZodAny>(
schema: T,
schemaObject: AnatineSchemaObject = {}
): T {
schema.metaOpenApi = Object.assign(schema.metaOpenApi || {}, schemaObject);
return schema;
const This = (schema as any).constructor;

Check warning on line 26 in packages/zod-openapi/src/lib/zod-openapi.ts

View workflow job for this annotation

GitHub Actions / build (18)

Unexpected any. Specify a different type
const newSchema = new This(schema._def);
newSchema.metaOpenApi = Object.assign(
{},
schema.metaOpenApi || {},
schemaObject
);
return newSchema;
}

function iterateZodObject({
Expand Down

0 comments on commit 6684ca6

Please sign in to comment.