Skip to main content

Getting Started

npm install --save @versionzero/configurator

There are three steps to using Configurator:

  1. Use Schema to define your configuration model.
  2. Initialize a Configurator instance with your schema.
  3. Call .configure() with context to load configuration from various sources.

Example

basics.js
import { Schema, Configurator } from '@versionzero/configurator';

const appName = 'basics';

// Define your configuration schema
const schema = new Schema('object')
.property('debug', new Schema('boolean').default(false))
.property(appName, new Schema('object')
.property('verbose', new Schema('boolean'))
.property('codes', new Schema('array').required()
.property('*', new Schema('string').validator('$alphanum'))
)
)
.property('server', new Schema('object')
.property('host', new Schema('string').default('127.0.0.1'))
.property('port', new Schema('number').default(80))
.property('protocol', new Schema('string').default('http').values(['http', 'https']))
);

// Load configuration from default sources
const config = await new Configurator({schema}).configure({
appName,
defaults: { [appName]: { verbose: true }}, // optional low priority source
overrides: { server: { protocol: 'https', port: 443 } } // optional high-priority override source
});

console.log('Configuration results:', config);

Try running it with a mix of environment variables and command line options:

% export BASICS_SERVER_HOST=localhost
% node basics.js --debug --server-port 8081 --codes 5xx z10 123

Configuration results: {
debug: true,
basics: { verbose: true, codes: [ '5xx', 'z10', '123' ] },
server: { host: 'localhost', port: 443, protocol: 'https' }
}

The mapping from schema properties to configuration inputs is largely "mechanical", but includes user-friendly accommodations such as automatically generating "short" command line aliases, and normalizing property names from different sources.

See the documentation in the ConfigurationSource category for the rules followed by each source.

The available command line options for this schema can be seen with --help:

% node basics.js --help
Usage: basics [options]
--codes (-c) <alphanum...> - (required)
--config (-C) [path|-] - load configuration from file (or - for stdin)
--debug (-d) [true|false] - (default:false)
--help (-h) [advanced] - display help information
--verbose (-v) [true|false]
--server-host (--sh) [string] - (default:127.0.0.1)
--server-port (--sp) [number] - (default:80)
--server-protocol [http|https] - (default:http)

(The .meta schema Metadata can be added to the schema to customize property and value descriptions.)