Skip to content

Commit

Permalink
fix(zod-openapi): no empty required to conform to OpenApi 3.0
Browse files Browse the repository at this point in the history
  • Loading branch information
OlivierCuyp committed Jan 16, 2023
1 parent e21f365 commit 5d7731e
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 14 deletions.
3 changes: 0 additions & 3 deletions packages/zod-openapi/src/lib/zod-openapi.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -139,7 +139,6 @@ describe('zodOpenapi', () => {
aStringRegex: { type: 'string', pattern: '^[a-zA-Z]+$' },
aStringNonEmpty: { type: 'string', minLength: 1 },
},
required: [],
description: 'This is totally unlike String Theory',
});
});
Expand Down Expand Up @@ -179,7 +178,6 @@ describe('zodOpenapi', () => {
aNumberLt: { type: 'number', maximum: 5, exclusiveMaximum: true },
aNumberMultipleOf: { type: 'number', multipleOf: 2 },
},
required: [],
description: 'Look mah, the horse can count higher than me!',
});
});
Expand Down Expand Up @@ -223,7 +221,6 @@ describe('zodOpenapi', () => {
items: { type: 'number' },
},
},
required: [],
description: 'I need arrays',
});
});
Expand Down
26 changes: 15 additions & 11 deletions packages/zod-openapi/src/lib/zod-openapi.ts
Original file line number Diff line number Diff line change
Expand Up @@ -188,6 +188,20 @@ function parseObject({
// So that `undefined` values don't end up in the schema and be weird
additionalProperties = additionalProperties ? { additionalProperties } : {};

const requiredProperties = Object.keys((zodRef as z.AnyZodObject).shape).filter((key) => {
const item = (zodRef as z.AnyZodObject).shape[key];
return (
!(
item.isOptional() ||
item instanceof z.ZodDefault ||
item._def.typeName === 'ZodDefault'
) &&
!(item instanceof z.ZodNever || item._def.typeName === 'ZodDefault')
);
});

const required = requiredProperties.length > 0 ? { required: requiredProperties } : {};

return merge(
{
type: 'object',
Expand All @@ -196,17 +210,7 @@ function parseObject({
schemas,
useOutput,
}),
required: Object.keys((zodRef as z.AnyZodObject).shape).filter((key) => {
const item = (zodRef as z.AnyZodObject).shape[key];
return (
!(
item.isOptional() ||
item instanceof z.ZodDefault ||
item._def.typeName === 'ZodDefault'
) &&
!(item instanceof z.ZodNever || item._def.typeName === 'ZodDefault')
);
}),
...required,
...additionalProperties,
},
zodRef.description ? { description: zodRef.description } : {},
Expand Down

0 comments on commit 5d7731e

Please sign in to comment.