Skip to content

Commit

Permalink
refactor: simplify undefined or empty checks in Zod preprocessors
Browse files Browse the repository at this point in the history
- Introduced a helper function `isUndefinedOrEmpty` to streamline checks for undefined or empty values.
- Updated `envNumber` and `envBoolean` methods to use the new helper function for improved readability.
  • Loading branch information
tuki0918 committed Dec 19, 2024
1 parent d2e3692 commit 8c0ef90
Showing 1 changed file with 4 additions and 3 deletions.
7 changes: 4 additions & 3 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,16 +15,17 @@ function validate<T extends ZodSchema>(
return result.data;
}

const isUndefinedOrEmpty = (v: unknown): boolean => v === undefined || v === "";

// Custom Zod methods
const envNumber = () =>
z.preprocess(
(v) => (v === undefined || v === "" ? undefined : Number(v)),
(v) => (isUndefinedOrEmpty(v) ? undefined : Number(v)),
z.number().int().nonnegative(),
);
const envBoolean = () =>
z.preprocess(
(v) =>
v === undefined || v === "" ? undefined : v === "true" || v === "1",
(v) => (isUndefinedOrEmpty(v) ? undefined : v === "true" || v === "1"),
z.boolean(),
);

Expand Down

0 comments on commit 8c0ef90

Please sign in to comment.