Skip to content

Commit

Permalink
Merge pull request #42 from nktpro/feature/zod-preprocessed-schemas
Browse files Browse the repository at this point in the history
Support zod preprocessed schemas
  • Loading branch information
AGalabov authored Oct 11, 2022
2 parents 3ea52d5 + 9d0c1fc commit 2652cc9
Show file tree
Hide file tree
Showing 2 changed files with 55 additions and 1 deletion.
53 changes: 53 additions & 0 deletions spec/simple.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -669,6 +669,59 @@ describe('Simple', () => {
});
});

describe('preprocessed', () => {
it('supports preprocessed string -> boolean schema', () => {
expectSchema(
[
z
.preprocess(arg => {
if (typeof arg === 'boolean') {
return arg;
}

if (typeof arg === 'string') {
if (arg === 'true') return true;
if (arg === 'false') return false;
}

return undefined;
}, z.boolean())
.openapi({ refId: 'PreprocessedBoolean' }),
],
{
PreprocessedBoolean: {
type: 'boolean',
},
}
);
});

it('supports preprocessed string -> number schema', () => {
expectSchema(
[
z
.preprocess(arg => {
if (typeof arg === 'number') {
return arg;
}

if (typeof arg === 'string') {
return parseInt(arg, 10);
}

return undefined;
}, z.number())
.openapi({ refId: 'PreprocessedNumber' }),
],
{
PreprocessedNumber: {
type: 'number',
},
}
);
});
});

it('does not support transformed schemas', () => {
expect(() =>
createSchemas([
Expand Down
3 changes: 2 additions & 1 deletion src/openapi-generator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -584,7 +584,8 @@ export class OpenAPIGenerator {

if (
isZodType(zodSchema, 'ZodEffects') &&
zodSchema._def.effect.type === 'refinement'
(zodSchema._def.effect.type === 'refinement' ||
zodSchema._def.effect.type === 'preprocess')
) {
const innerSchema = zodSchema._def.schema as ZodSchema<any>;
return this.generateInnerSchema(innerSchema);
Expand Down

0 comments on commit 2652cc9

Please sign in to comment.