Skip to content

Commit 1cee930

Browse files
committed
fix(zod): zod to json schema not covert zod description
1 parent 0f053ee commit 1cee930

File tree

2 files changed

+50
-0
lines changed

2 files changed

+50
-0
lines changed

packages/zod/src/converter.test.ts

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -389,3 +389,34 @@ describe('with custom json schema', () => {
389389
})
390390
})
391391
})
392+
393+
it('zod description', () => {
394+
const schema = z.object({
395+
name: z.string().describe('name description'),
396+
397+
nested: z.object({
398+
name: z.string().describe('nested name description'),
399+
}),
400+
})
401+
402+
expect(zodToJsonSchema(schema)).toEqual({
403+
type: 'object',
404+
properties: {
405+
name: {
406+
type: 'string',
407+
description: 'name description',
408+
},
409+
nested: {
410+
type: 'object',
411+
properties: {
412+
name: {
413+
type: 'string',
414+
description: 'nested name description',
415+
},
416+
},
417+
required: ['name'],
418+
},
419+
},
420+
required: ['name', 'nested'],
421+
})
422+
})

packages/zod/src/converter.ts

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -105,6 +105,13 @@ export interface ZodToJsonSchemaOptions {
105105
* @internal
106106
*/
107107
isHandledCustomJSONSchema?: boolean
108+
109+
/**
110+
* Track if current level schema is handled zod description to prevent recursive
111+
*
112+
* @internal
113+
*/
114+
isHandledZodDescription?: boolean
108115
}
109116

110117
export function zodToJsonSchema(
@@ -118,6 +125,18 @@ export function zodToJsonSchema(
118125

119126
const schema__ = schema as ZodTypeAny
120127

128+
if (!options?.isHandledZodDescription && 'description' in schema__._def) {
129+
const json = zodToJsonSchema(schema__, {
130+
...options,
131+
isHandledZodDescription: true,
132+
})
133+
134+
return {
135+
description: schema__._def.description,
136+
...json,
137+
}
138+
}
139+
121140
if (!options?.isHandledCustomJSONSchema) {
122141
const customJSONSchema = getCustomJSONSchema(schema__._def, options)
123142

0 commit comments

Comments
 (0)