1.0.0 • Published 10 months ago

@gpa/simple-typed-env v1.0.0

Weekly downloads
-
License
MIT
Repository
gitlab
Last release
10 months ago

@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 and boolean.
  • 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 and 1 for true, and false, no and 0 for false (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.