@samhuk/env-parser
v0.0.5
Published
Powerful Typescript environment variable parser
Downloads
5
Readme
Overview
env-parser is a powerful, fully type-enforced Node environment variable parser. It supports environment type inference, arbitrary parsing and validation, and recursive property nesting.
Why use?
env-parser combines a set of features that together no other environment variable parser package has:
- Delightful type inference of your environment according to your description of it.
- Recursive property nesting.
- Robust validation and error handling functionality.
Usage Overview
Parse environment variables, from process.env
by default or manually provided:
import parseEnv from '@samhuk/env-parser'
// -- Define any common validators
const isNumberBetween = (l: number, u: number) => (
(v: number) => !Number.isNaN(v) && v > l && v < u
)
const isNonNegativeNumber = (v: number) => !Number.isNaN(v) && v > 0
// -- Mock process env (process.env is used by default)
const processEnv = {
SERVER_PORT: '4001',
SERVER_HOST: '10.0.0.1',
NODE_ENV: 'production',
DB_HOST: 'localhost',
DB_PORT: '5432',
DB_NAME: 'test-db',
DB_OTHER_OPTIONS_TIMEOUT_SECONDS: '1000',
ADMIN_USER_NAMES: '["root", "admin", "administrator"]',
ENABLE_DATA_SCRAPE: '1',
}
// -- Parse env
const envResult = parseEnv({
serverPort: { $default: 8080 },
serverHost: { $default: 'localhost' },
isProd: { $name: 'NODE_ENV', $default: false, $parse: v => v === 'production' },
db: {
host: { $default: 'localhost' },
port: { $default: 5432, $validate: isNumberBetween(80, 60000) },
name: { $default: 'db' },
otherOptions: {
timeoutSeconds: { $default: 1000, $validate: isNonNegativeNumber },
},
},
adminUserNames: { $parse: 'arr' },
enableDataScrape: { $parse: 'bool' },
}, processEnv)
// -- Observe parse result!
console.log(envResult.value)
/* {
serverPort: 4001,
serverHost: '10.0.0.1',
isProd: true,
db: {
host: 'localhost',
port: 5432,
name: 'test-db',
otherOptions: {
timeoutSeconds: 1000,
},
},
adminUserNames: ['root', 'admin', 'administrator'],
enableDataScrape: true,
}) */
console.log(envResult.hasErrors) // false
console.log(envResukt.errors) // []
The parsed environment is fully typed according to your description of it:
type Env = typeof envResult['value']
/* type Env = {
serverPort: number;
serverHost: string;
isProd: boolean;
db: {
host: string;
port: number;
name: string;
otherOptions: {
timeoutSeconds: number;
};
};
} */
Development
Contributions welcome. See ./contributing/development.md.
If you found this package delightful, feel free to buy me a coffee ✨
Package generated from ts-npm-package-template