Kojak
(Named after an Irish Setter in a Stephen King novel, because all the better names are taken)
A simple configuration container class, designed for handling settings objects easily. Design considerations:
- support environment-based property choices at any depth
- provide a native interface for getting and setting (no special methods required)
- support modification after creation
- support environment-changes after creation
It's a known limitation that convoluted series of setting a mix of keys and objects may result in unintuitive results - things set directly take precedence over objects set afterwards due to internal design. For sanity, either always set things using objects, or only use objects during the constructor phase and thereafter set directly on keys (e.g. settings.foo = 'bar'
instead of settings.set({foo: 'bar'}
where possible)
API
new Kojak([one, [two, [...])
Creates a new settings object with optional properties provided during creation
.set(value, override = true)
Adds an object to the Kojak collection, making top-level keys from the value available as top-level keys on the Kojak object. override
defines if the new data should take preccedence over existing data.
.set(path, value, override = true)
Adds the defined path to the Kojak collection. A path is either a simple key name or a dot-separated path. It uses Lodash _.set internally.
.get(path, default)
Returns the value at the provided path, or the default if it is undefined. It uses Lodash _.get internally.
.setEnv(name)
Changes the chosen environment for path-resolution.
.useEnv(options)
Imports properties from process.env
according to provided options.
settings
Examples
Basic usage, with a nested environment branch
// NODE_ENV=developmentlet settings = color: production: 'blue' development: 'green' ;console // 'green'
A top-level environment branch
// NODE_ENV=productionlet settings = production: color: 'blue' development: color: 'green' ;console // 'blue'
Importing parameters from envvars
// NODE_PORT=9182, NESTED__VALUE=hellolet settings = ;settings;console; // '9182'console; // 'hello'
Importing some parameters from envvars
// NODE_PORT=9182, NESTED__VALUE=hellolet settings = ;settings;console; // 9182
Getting a nested value with a default
let settings = ;settingsconsole // 'white'console // 'blank'
Setting default-values after other things
let settings = color: 'white' settings; // false signifies it's a defaultconsole // 'white'console // 'large'
Setting default values during construction
let defaults = color: 'white' size: 'large';let settings = defaults color: 'blue'; // right-most values take precedence console // 'blue'console // 'large'