Skip to content

Commit 9366d0f

Browse files
committed
Add depictObject to correct required props on requests.
1 parent 5e6347e commit 9366d0f

2 files changed

Lines changed: 18 additions & 4 deletions

File tree

express-zod-api/src/documentation-helpers.ts

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import type {
2+
$ZodObject,
23
$ZodPipe,
34
$ZodTransform,
45
$ZodTuple,
@@ -209,6 +210,18 @@ export const depictLiteral: Depicter = ({ jsonSchema }) => ({
209210
...jsonSchema,
210211
});
211212

213+
const depictObject: Depicter = ({ zodSchema, jsonSchema }, { isResponse }) => {
214+
if (isResponse) return jsonSchema;
215+
if (!isSchema<$ZodObject>(zodSchema, "object")) return jsonSchema;
216+
const { required = [] } = jsonSchema as JSONSchema.ObjectSchema;
217+
const result: string[] = [];
218+
for (const key of required) {
219+
const valueSchema = zodSchema._zod.def.shape[key];
220+
if (valueSchema && !doesAccept(valueSchema, undefined)) result.push(key);
221+
}
222+
return { ...jsonSchema, required: result };
223+
};
224+
212225
const ensureCompliance = ({
213226
$ref,
214227
type,
@@ -467,6 +480,7 @@ const depicters: Partial<Record<FirstPartyKind | ProprietaryBrand, Depicter>> =
467480
pipe: depictPipeline,
468481
literal: depictLiteral,
469482
enum: depictEnum,
483+
object: depictObject,
470484
[ezDateInBrand]: depictDateIn,
471485
[ezDateOutBrand]: depictDateOut,
472486
[ezUploadBrand]: depictUpload,

express-zod-api/tests/__snapshots__/documentation.spec.ts.snap

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -956,7 +956,7 @@ paths:
956956
type: string
957957
- name: optDefault
958958
in: query
959-
required: true
959+
required: false
960960
description: GET /v1/getSomething Parameter
961961
schema:
962962
type: string
@@ -971,7 +971,7 @@ paths:
971971
- "null"
972972
- name: nuDefault
973973
in: query
974-
required: true
974+
required: false
975975
description: GET /v1/getSomething Parameter
976976
schema:
977977
type:
@@ -2147,7 +2147,7 @@ paths:
21472147
parameters:
21482148
- name: any
21492149
in: query
2150-
required: true
2150+
required: false
21512151
description: GET /v1/getSomething Parameter
21522152
schema: {}
21532153
responses:
@@ -2224,7 +2224,7 @@ paths:
22242224
parameters:
22252225
- name: string
22262226
in: query
2227-
required: true
2227+
required: false
22282228
description: GET /v1/getSomething Parameter
22292229
schema:
22302230
format: string (preprocessed)

0 commit comments

Comments
 (0)