Skip to content

Commit 2546825

Browse files
authored
feat(zod): support readOnly, propertyNames in JSON schema (#211)
* feat(zod): support the readOnly flag in JSON schemas * feat(zod): support the propertyNames in JSON schemas
1 parent 4534675 commit 2546825

File tree

2 files changed

+16
-3
lines changed

2 files changed

+16
-3
lines changed

packages/zod/src/converter.test.ts

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -296,7 +296,8 @@ const processedCases: SchemaTestCase[] = [
296296
},
297297
{
298298
schema: z.number().readonly(),
299-
input: [true, { type: 'number' }],
299+
input: [true, { type: 'number', readOnly: true }],
300+
ignoreZodToJsonSchema: true,
300301
},
301302
]
302303

@@ -399,6 +400,11 @@ const edgeCases: SchemaTestCase[] = [
399400
schema: z.object({ value: z.string() }).catchall(z.number()),
400401
input: [true, { type: 'object', properties: { value: { type: 'string' } }, required: ['value'], additionalProperties: { type: 'number' } }],
401402
},
403+
{
404+
schema: z.record(z.number(), z.string()),
405+
input: [true, { type: 'object', additionalProperties: { type: 'string' }, propertyNames: { type: 'number' } }],
406+
ignoreZodToJsonSchema: true,
407+
},
402408
]
403409

404410
describe.each([

packages/zod/src/converter.ts

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -413,7 +413,12 @@ export class ZodToJsonSchemaConverter implements ConditionalSchemaConverter {
413413

414414
const json: JSONSchema = { type: 'object' }
415415

416-
// WARN: ignore keyType
416+
const keyTypeName = this.#getZodTypeName(schema_._def.keyType._def)
417+
418+
if (keyTypeName !== ZodFirstPartyTypeKind.ZodString) {
419+
const [_, keyJson] = this.convert(schema_._def.keyType, options, lazyDepth, false, false)
420+
json.propertyNames = keyJson
421+
}
417422

418423
const [_, itemJson] = this.convert(schema_._def.valueType, options, lazyDepth, false, false)
419424

@@ -524,7 +529,9 @@ export class ZodToJsonSchemaConverter implements ConditionalSchemaConverter {
524529

525530
case ZodFirstPartyTypeKind.ZodReadonly: {
526531
const schema_ = schema as ZodReadonly<ZodTypeAny>
527-
return this.convert(schema_._def.innerType, options, lazyDepth, false, false)
532+
const [required, json] = this.convert(schema_._def.innerType, options, lazyDepth, false, false)
533+
534+
return [required, { ...json, readOnly: true }]
528535
}
529536

530537
case ZodFirstPartyTypeKind.ZodDefault: {

0 commit comments

Comments
 (0)