Détail du package

@logdna/env-config

logdna1kSEE LICENSE IN LICENSE2.0.1

Configuration package for reading environment variables

env, env var, environemnt, config

readme

Coverage Status All Contributors

@logdna/env-config

Node.js Package to define, document, and assert environment variables

Install

$ npm install --save @logdna/env-config

Test

$ npm t

Usage

The recommended way to structure applications with this package is as follows:

// config.js

'use strict'

const Config = require('@logdna/env-config')
const config = new Config([
  Config.string('loglevel').default('info')
, Config.number('port').default(3000)
])

module.exports = config
// index.js
//
// The following env vars can be set:
//
// LOGLEVEL - defaults to info
// PORT - default to 3000
//

'use strict'

const http = require('http')
const config = require('./config.js')

// This validates that we have the necessary env vars.
config.validateEnvVars()

http.listen(config.get('port'), () => {
  log.info('listen', config.get('port'))
})

Under the hood, Config is a <Map>, so use it like one.

This package also provides a way to automatically generate documentation for the environment variables for a service.

If the doc directory does not exist, it can be created using the following:

$ mkdir -p doc

Then, add a generate script to the service's package.json that looks similar to this:

config-doc config.js > doc/env.md

You should also add a link to this document in the README.md of the service.

API

new Config(input)

  • input <Array> Array of objects that represent a single rule.

Each input item should be a Definition. See "Static Methods" below.

Static Methods


The following static methods return a Definition that can be used.

Config.string(name)

  • name <String> Name of the config rule. The environment variable read for this rule will be name uppercased with - replaced with _.

This defines a configuration definition for an environment variable that is a <String>.

Returns: Definition

Config.number(name)

  • name <String> Name of the config rule. The environment variable read for this rule will be name uppercased with - replaced with _.

This defines a configuration defintion for an environment variable that is a <Number>.

Returns: Definition

Config.boolean(name)

  • name <String> Name of the config rule. The environment variable read for this rule will be name uppercased with - replaced with _.

This defines a configuration definition for an environment variable that is a <Boolean>.

Returns: Definition

Config.regex(name)

  • name <String> Name of the config rule. The environment variable read for this rule will be name uppercased with - replaced with _.

This defines a configuration definition for an environment variable that matches a <RegExp>.

Returns: Definition

Config.enum(name)

  • name <String> Name of the config rule. The environment variable read for this rule will be name uppercased with - replaced with _.

A single value will be read from the environment variable as described, but it must exist in the allowed list of .values(). Every enum type needs to implement a .values() array.

Config.list(name)

  • name <String> Name of the config rule. The environment variable read for this rule will be name uppercased with - replaced with _.

Much like a CSV - an environment variable will be read and parsed into an array of a specific type. The type can be of string, boolean, or number. This is defined by calling .type(). All empty values generated by trailing characters are removed

Instance Methods


Config#toJSON()

Returns a JSON representation of the config object. This will only work for Primitive values, objects, and arrays.

Config#validateEnvVars()

This should be called to validate that the required environment variables have been passed and that they satisfy the requirements. If any are not passed, or do not satisfy the requirements, an error will be thrown.

Definition

This is a private prototype that offers the following methods:

Definition#required()

Specifies that this env var is required to have a value (env vars are optional by default). This means that a value must be provided, and it cannot be the empty string, ''.

Returns this to allow chaining.

Definition#desc(str)

This sets the description for the env var that will be used for docs. This is an alias for the Definition#description(str) method.

Returns this to allow chaining.

Definition#description(str)

This sets the description for the env var that will be used for docs.

Returns this to allow chaining.

Definition#default(def)

This sets the default value of the rule. This does not set the actual env var, but the value in the config's <Map> will show the default value if the env var's value is empty.

The default value will be applied for an unset var as well as a value of ''.

Returns this to allow chaining.

Definition#allowEmpty()

allowEmpty() tells the definition to accept an empty value in place of the provided non-empty .default() for cases where an empty value is valid and/or expected. Without this option, the default value will be used when an empty value is detected for a given type. A common use for this is to allow '' as a value for a .string() definition. In other words, allowEmpty() is a no-op without a default().

The empty values for the config types supported by this package are as follows:

Type Final Value
string ''
number 0
boolean false
list []

Definition#toJSON()

Returns a JSON representation of the configuration Definition.

Definition#match(re)

This method can only be used with Config.regex(). Otherwise, an error will be thrown.

Returns this to allow chaining.

Definition#min(n)

  • n <Number> The minimum value for the rule

This method can only be used with Config.number(). Otherwise, an error will be thrown.

Returns this to allow chaining.

Definition#max(n)

  • n <Number> The maximum value for the rule

This method can only be used with Config.number(). Otherwise, an error will be thrown.

Returns this to allow chaining.

Definition#values(arr)

  • arr <Array> An array of acceptable values for an enum type.

This method can only be used with Config.enum(). The final value must exist in the values arr, or an error is thrown.

Definition#type(type)

  • type <String> The type of value expected within a list can be one of:
    • number
    • boolean
    • string

Definition#separator(value)

default: /\s+|,/

Custom Errors

'MissingEnvError'

  • <Error>
    • name <String> Static value of MissingEnvError
    • type <String> Describes the definition: string, number, boolean, regex, or enum

This error is thrown if Definition#required was used, but no such environment variable or value was discovered.

'RequiredDefaultMutexError'

  • <Error>
    • name <String> Static value of RequiredDefaultMutexError
    • type <String> Describes the definition: string, number, boolean, regex, or enum

This error is thrown if Definition#required and Definition#default are used together in a definition. A non-empty value must be provided for required variables, thus setting a default value for those is a dead code path. These two options are mutually exclusive.

'RegExpError'

  • <Error>
    • name <String> Static value of RegExpError
    • expected <RegExp> The regular expression that is expected to match the discovered value
    • actual (Any) The value that was discovered in the environment
    • env <String> The name of the evironment variable that is supposed to hold the value (upper cased with underscores, e.g. MY_VARIABLE)

This error is thrown if Config.regex() was used, but the discovered value in the environment did not match the pattern.

'EnumError'

  • <Error>
    • name <String> Static value of EnumError
    • expected <Array> The list of acceptable values for the definition
    • actual (Any) The value that was discovered in the environment
    • env <String> The name of the evironment variable that is supposed to hold the value (upper cased with underscores, e.g. MY_VARIABLE)

This error is thrown if Config.regex() was used, but the discovered value in the environment did not match the pattern.

'ListError'

  • <Error>
    • name <String> Static value of EnumError
    • expected <Array> The list of acceptable values for the definition
    • actual (Any) An invalid value that found withing the list
    • input <String> The the value of the environment variable after it was parsed and sanitized
    • original <String> The original value from the environment variable
    • type <String> The defined value type of the list property
    • env <String> The name of the evironment variable that is supposed to hold the value (upper cased with underscores, e.g. MY_VARIABLE)

This error is thrown if Config.list() was used, but the discovered value in the environment contained an invalid value

Contributors ✨

Thanks goes to these wonderful people (emoji key):


Evan Lucas

💻 📖

Darin Spivey

💻 📖

Jacob Hull

🚧

Eric Satterwhite

💻

This project follows the all-contributors specification. Contributions of any kind welcome!

changelog

Changelog

2.0.1 (2022-06-09)

Bug Fixes

  • Do not throw errors until validateEnvVars is called 8afa07d - Darin Spivey

2.0.0 (2022-06-09)

Bug Fixes

  • Correct boolean test to not use required 6f730aa - Darin Spivey

Code Refactoring

  • A value of empty string should apply the default value 1c93bba - Darin Spivey

Features

  • allowEmpty() will allow '' to be a valid value f46bb1d - Darin Spivey

Miscellaneous

  • CI test with newer versions of node bb2482e - Darin Spivey
  • eslint-config-logdna@6.1.0 c48ec52 - Darin Spivey
  • tap@16.2.0 ec66875 - Darin Spivey

Style

  • Give custom errors their own files 59c3811 - Darin Spivey

BREAKING CHANGES

  • This change affects the way that default values are assigned, and the default value will now be used if the env var's value is ''. Also, using .required() and .default() in the same definition will now result in a mutex error.

1.1.0 (2021-04-16)

Features

  • expose a list type 19b5c0d - Eric Satterwhite

Miscellaneous

  • add @esatterwhite as a contributor a8012ac - Eric Satterwhite

1.0.5 (2021-02-16)

Bug Fixes

  • Replace .npmignore with files whitelist b0f3e68 - Darin Spivey

Miscellaneous

  • add @darinspivey as a contributor 4c79cd0 - Darin Spivey
  • add @evanlucas as a contributor 9f923ab - Darin Spivey
  • add @jakedipity as a contributor 7d56f16 - Darin Spivey
  • eslint-config-logdna@4.0.2 d73e31d - Darin Spivey
  • Install and use semantic release b93ddfc - Darin Spivey

2021-02-11, Version 1.0.4 (Stable)

  • [464835d214] - fix: Change branch to main and add contributors (Darin Spivey)

2020-10-30, Version 1.0.3 (Stable)

2020-10-16, Version 1.0.2 (Stable)

2020-10-02, Version 1.0.1 (Stable)

2020-10-01, Version 1.0.0 (Stable)

  • [ee130ccbab] - (SEMVER-MAJOR) package: Open source the env config package (Darin Spivey) LOG-7311