Getting Started
There are three steps to using Configurator:
- Use a
Schemato define your configuration model. - Initialize a
Configuratorinstance with yourSchema. - Call
.configure()with application context to load configuration settings.
Example
% npm install --save @versionzero/configurator
basics.js
import { Configurator, Schema } from '@versionzero/configurator';
const appName = 'basics';
// Define your configuration schema
const schema = new Schema('object')
.property('debug', new Schema('boolean').default(false).meta('flagHint', 'D'))
.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,
// automatically populated into context if you use the command line below:
// argv: ['-D', '--server-port', '8081', '--codes', '5xx', 'z10', '123'],
// env: ['BASICS_SERVER_HOST=localhost'],
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 -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 properties to configuration inputs is largely "mechanical", but includes user-friendly accommodations such as automatically generating flags or "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)
You can add metadata to the schema using .meta() that sources can use to customize behavior,
such as setting descriptions or flag hints for the CLI.