type-env

Type safe way defining configurations fed by environment variables, process arguments or json config files (including deserialization and validation)

Downloads in past

Stats

StarsIssuesVersionUpdatedCreatedSize
type-env
1.1.04 years ago5 years agoMinified + gzip package size for type-env in KB

Readme

Build Status codecov
type-env
Type safe way defining configurations fed by environment variables, process arguments or json config files (including deserialization and validation).

Installation

npm install type-env --save
type-env requires reflect-metadata
npm install reflect-metadata --save
Your tsconfig.json needs the following flags:
{
  "experimentalDecorators": true,
  "emitDecoratorMetadata": true
}

Getting started

Setup configuration class

import {Config, EnvValue} from 'type-env';
@Config
class DataBaseConfiguration {
    @EnvValue('DB_HOST') host: string = 'localhost'; // default value
    @EnvValue('DB_NAME') name: string;
    @EnvValue('DB_PORT') port: number;
}
import {Config, ArgsValue} from 'type-env';
@Config
class LoggingConfiguration {
    @ArgsValue('log-level') level: string;
    @ArgsValue('silent') silent: boolean;
}
{
  "auth": {
    "jwt": {
      "issuer": "type-env"
    },
    "timestamp": "2018-05-27T17:35:54.391Z"
  }
}
import {Config, JsonConfiguration, JsonValue} from 'type-env';
@Config
@JsonConfiguration(`${__dirname}/config.json`)
class AuthConfiguration {
    @JsonValue('auth.jwt.issuer') jwtIssuer: string = 'type-env';
    @JsonValue('auth.timestamp') timestamp: Date;
}

Run application

DB_HOST='127.0.0.1' /
DB_NAME='type-env' /
DB_PORT='1234' /
node app.js --log-level info --silent

Options

import {buildDecorators, NodeEnvConfigSource, NodeArgsConfigSource, JsonConfigSource} from 'type-env';

const {Value, EnvValue, ArgsValue, JsonValue} = buildDecorators({
    /**
     * Enables validation if true. Throws if config value is invalid.
     * @default true
     */
    validate: true,
    
    /**
     * Throws if value does not exist on source.
     * @default true
     */
    required: true,
    
    /**
     * If true, loads config value when property is accessed.
     * @default true
     */
    lazyLoad: true,

    /**
     * Do not throw on validation or requirement errors, but logs a warning instead.
     * @default false
     */
    warnOnly: false,
    
    /**
     * Map of decorator key name and config source.
     * @default {
                    Value: NodeEnvConfigSource,
                    EnvValue: NodeEnvConfigSource,
                    ArgsValue: NodeArgsConfigSource,
                    JsonValue: JsonConfigSource,
                }
     */
    decoratorMeta: {
        Value: NodeEnvConfigSource,
        EnvValue: NodeEnvConfigSource,
        ArgsValue: NodeArgsConfigSource,
        JsonValue: JsonConfigSource,
    }
})