scenv-zod
v0.4.0
Published
Zod parser for scenv variables
Readme
scenv-zod
Zod-based parser for scenv. Use Zod schemas to parse variable values; input from env/context/CLI is string, so use z.coerce.number(), etc. Default and variable output type are the parsed type T.
Install
pnpm add scenv scenv-zod zod
# or
npm install scenv scenv-zod zodPeer dependencies: scenv, zod (^3.22.0).
Usage
Pass parser(schema) as the parser option to scenv(). The schema can coerce strings to numbers, booleans, etc.
import { scenv } from "scenv";
import { parser } from "scenv-zod";
import { z } from "zod";
const port = scenv("Port", {
key: "port",
env: "PORT",
default: 3000,
parser: parser(z.coerce.number().min(1).max(65535)),
});
const debug = scenv("Debug", {
key: "debug",
default: false,
parser: parser(
z.union([z.boolean(), z.literal("true"), z.literal("false")])
.transform((v) => v === true || v === "true")
),
});
const portNum = await port.get(); // number
const isDebug = await debug.get(); // booleanParsing runs during .get() / .safeGet(). On failure, .get() throws; .safeGet() returns { success: false, error } with the Zod error.
API
| Export | Description |
|--------|-------------|
| parser(schema) | Returns a function (val: unknown) => { success: true, data } \| { success: false, error } compatible with scenv's parser option. |
License
MIT
