Skip to main content

Getting Started

npm install --save @versionzero/configurator

There are three steps to using Configurator:

  1. Use a ConfigurationSchema to define your configuration model.
  2. Initialize a Configurator with your schema to manage the configuration process.
  3. Call configure with context for the various configuration sources.

Example

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

const appName = 'basics';
// Define your configuration schema
const schema = new ConfigurationSchema();

schema.field('debug', { type: 'boolean', flagHint: 'D', advanced: true })

schema.child(appName)
.field('verbose', { type: 'boolean' })
.field('codes', { type: 'array', validator: {$each: '$alphanum'}, required: true})
schema.child('server')
.field('host', { default: '127.0.0.1' })
.field('port', { type: 'number', default: 80, validator: '$positive'})
.field('protocol', { validator: {$in: ['tcp', 'udp', 'https', 'http']}})

// Initialize the configurator with your schema
const config = await new Configurator({schema}).configure({
appName, // application name
defaults: { [appName]: { verbose: true }}, // optional low priority source, but higher than field defaults
env: process.env, // (unnecessary, this is the default value)
argv: process.argv, // (unnecessary, this is the default value)
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 -D --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 fields to configuration inputs is largely "mechanical", but includes user-friendly accommodations such as automatically generating "short" command line aliases, and truncating the child name prefix when it matches the app name.

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