Skip to content

Commit

Permalink
Warn instead of throwing for unsupported types
Browse files Browse the repository at this point in the history
closes #9
  • Loading branch information
matejchalk committed Feb 19, 2025
1 parent 8ce403f commit d0b6517
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 7 deletions.
38 changes: 36 additions & 2 deletions src/converter/convert-schemas.spec.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { z } from 'zod';
import { z, ZodType, type ZodTypeDef } from 'zod';
import type { NamedModel } from '../types';
import { convertSchemas } from './convert-schemas';

Expand Down Expand Up @@ -207,6 +207,40 @@ describe('convert exported Zod schemas to models', () => {
]);
});

it('should warn if type unsupported and use never', () => {
vi.spyOn(console, 'warn').mockReturnValue();

expect(
convertSchemas([
{ path: 'schemas.ts', name: 'ID', schema: z.string().brand('ID') },
{
path: 'schemas.ts',
name: 'Experimental',
schema: {
_def: { typeName: 'ZodExperimental' } as ZodTypeDef,
isOptional: () => false,
isNullable: () => false,
} as ZodType,
},
])
).toEqual<NamedModel[]>([
{
type: 'string',
name: 'ID',
path: 'schemas.ts',
},
{
type: 'never',
name: 'Experimental',
path: 'schemas.ts',
},
]);

expect(console.warn).toHaveBeenCalledWith(
`WARNING: Zod type ZodExperimental is not supported, using never.\nIf you'd like support for ZodExperimental to be added, please create an issue: https://github.com/matejchalk/zod2md/issues/new`
);
});

it('should support the ZodPipeline type', () => {
const PostalCodeSchema = z
.string()
Expand All @@ -219,7 +253,7 @@ describe('convert exported Zod schemas to models', () => {
convertSchemas([
{ path: 'postalcode.ts', schema: PostalCodeSchema, name: 'PostalCode' },
])
).toEqual(<NamedModel[]>[
).toEqual<NamedModel[]>([
{
name: 'PostalCode',
path: 'postalcode.ts',
Expand Down
17 changes: 12 additions & 5 deletions src/converter/convert-schemas.ts
Original file line number Diff line number Diff line change
Expand Up @@ -258,11 +258,18 @@ function convertSchema(
};
}

throw new Error(
`Zod type ${
'typeName' in schema._def ? schema._def.typeName : '<unknown>'
} is not supported`
);
const typeName = 'typeName' in schema._def ? schema._def.typeName : null;
const message = [
`WARNING: Zod type ${
typeName ?? '<unknown>'
} is not supported, using never.`,
typeName &&
`If you'd like support for ${typeName} to be added, please create an issue: https://github.com/matejchalk/zod2md/issues/new`,
]
.filter(Boolean)
.join('\n');
console.warn(message);
return { type: 'never' };
}

function convertZodArray(
Expand Down

0 comments on commit d0b6517

Please sign in to comment.