@gpa/simple-typed-env
v1.0.0
Published
Simple type-safe environment variable parser
Downloads
2
Maintainers
Readme
@gpa/simple-typed-env
Simple environment variable parser providing an automatically typed object from the passed configuration
Very basic implementation, for more complex use cases you can check out envalid and env-var.
Install
npm install @gpa/simple-typed-env
Usage
import { parseEnv } from '@gpa/simple-typed-env';
// process.env.STRING = 'a string'
// process.env.STRING_ARRAY = 'string1,string2'
// process.env.BOOL = true
// process.env.NUMBER = -123.4
const env = parseEnv({
STRING: 'string',
STRING_ARRAY: 'string[]',
BOOL: 'boolean',
NUMBER: 'number',
OPTIONAL: 'string?',
});
// => typeof env = {
// STRING: string;
// STRING_ARRAY: string[],
// BOOL: boolean,
// NUMBER: number,
// OPTIONAL: string | undefined,
// }
// => env === {
// STRING: 'a string',
// STRING_ARRAY: ['string1', 'string2'],
// BOOL: true,
// NUMBER: -123.4,
// OPTIONAL: undefined,
// }
API
parseEnv(config)
config
Type: object
- The keys of this object are the names of the environment variables to be parsed, and the corresponding values are the expected type.
- The accepted values for the types are
string
,number
andboolean
. - Square brackets can be appended to expect an array of value (comma separated):
string[]
. - A question mark can be appended to denote an optional value:
number?
. - Brackets and question mark can be combined:
string[]?
. - Any value not marked as optional will result in an error being thrown when calling
parseEnv()
if the related environment variable does not exist or is an empty string.
Returned value
Type: object
A simple object with a key-value pair for each declared variable in the config
parameter.
- Accepted values for booleans are
true
,yes
and1
fortrue
, andfalse
,no
and0
forfalse
(case-insensitive). - Optional values for which no environment variable exists, or for which the environment variable is empty will be returned as
undefined
. - The returned object will be correctly typed according to the passed configuration.