Skip to content

Commit a505809

Browse files
committed
Handle ZodCatch which throws
1 parent 245c12d commit a505809

File tree

2 files changed

+23
-5
lines changed

2 files changed

+23
-5
lines changed

src/converter/convert-schemas.spec.ts

Lines changed: 13 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -350,7 +350,19 @@ describe('convert exported Zod schemas to models', () => {
350350
});
351351

352352
it('should support the ZodCatch type', () => {
353-
const permissiveUrlSchema = z.string().url().catch('');
353+
const permissiveUrlSchema = z
354+
.string()
355+
.url()
356+
.catch(ctx => {
357+
if (
358+
ctx.error.errors.length === 1 &&
359+
ctx.error.errors[0]?.code === 'invalid_string' &&
360+
ctx.error.errors[0].validation === 'url'
361+
) {
362+
return '';
363+
}
364+
throw ctx.error;
365+
});
354366

355367
expect(
356368
convertSchemas([
@@ -366,8 +378,6 @@ describe('convert exported Zod schemas to models', () => {
366378
path: 'utils.ts',
367379
type: 'string',
368380
validations: ['url'],
369-
nullable: true,
370-
optional: true,
371381
},
372382
]);
373383
});

src/converter/convert-schemas.ts

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -138,10 +138,18 @@ function schemaToMeta(
138138
schema: ZodType<unknown>,
139139
implicitOptional?: boolean
140140
): Omit<ModelMeta, 'default'> {
141+
const safeCheck = (is: () => boolean) => {
142+
try {
143+
return is();
144+
} catch {
145+
return false;
146+
}
147+
};
141148
return {
142149
...(schema.description && { description: schema.description }),
143-
...(!implicitOptional && schema.isOptional() && { optional: true }),
144-
...(schema.isNullable() && { nullable: true }),
150+
...(!implicitOptional &&
151+
safeCheck(schema.isOptional) && { optional: true }),
152+
...(safeCheck(schema.isNullable) && { nullable: true }),
145153
};
146154
}
147155

0 commit comments

Comments
 (0)