Getting Started
npm install --save @versionzero/configurator
There are three steps to using Configurator:
- Use a
ConfigurationSchemato define your configuration model. - Initialize a
Configuratorwith your schema to manage the configuration process. - Call
configurewith 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.