Skip to content

Commit 6697c41

Browse files
committed
Ref: simpler isOptional.
1 parent 8ff68f3 commit 6697c41

1 file changed

Lines changed: 14 additions & 7 deletions

File tree

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

Lines changed: 14 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,9 @@
1-
import type { $ZodObject, $ZodTransform, $ZodType } from "@zod/core";
1+
import type {
2+
$ZodObject,
3+
$ZodTransform,
4+
$ZodType,
5+
$ZodTypeInternals,
6+
} from "@zod/core";
27
import { Request } from "express";
38
import * as R from "ramda";
49
import { globalRegistry, z } from "zod";
@@ -170,15 +175,17 @@ export const getTransformedType = R.tryCatch(
170175
R.always(undefined),
171176
);
172177

178+
const requestOptionality: Array<$ZodTypeInternals["optionality"]> = [
179+
"optional",
180+
"defaulted",
181+
];
173182
export const isOptional = (
174-
subject: $ZodType,
183+
{ _zod: { optionality } }: $ZodType,
175184
{ isResponse }: { isResponse: boolean },
176-
) => {
177-
const { optionality } = subject._zod;
178-
return isResponse
185+
) =>
186+
isResponse
179187
? optionality === "optional"
180-
: optionality === "optional" || optionality === "defaulted";
181-
};
188+
: optionality && requestOptionality.includes(optionality);
182189

183190
/** @desc can still be an array, use Array.isArray() or rather R.type() to exclude that case */
184191
export const isObject = (subject: unknown) =>

0 commit comments

Comments
 (0)