1.0.5 • Published 5 years ago
@itemsjs/config v1.0.5
ItemsJS config
Load your application configuration from different sources with your own priority
Installation
npm i @itemsjs/config --save
Usage
const Config = require('@itemsjs/config');
// Pass an object as default configuration model (it's optional)
const config = new Config({
appName: 'my-custom-app-name',
version: '1.23'
});
// Built-in providers
// 1) args (parse command-line arguments)
// 2) env (parse environment variables that prefixed by a specific prefix)
// 3) json (parse JSON file)
// 4) yaml (parse Yaml file)
// 5) obj (Use your own store to read configuration and use this method to apply it. Somehow default configuration behavior)
// to load configuration using a provider, you have two choices
// 1) the first choice (using provider name)
config.load('json', 'path-to-json-file', {})
.then(cfg => {
// cfg refers to the main instance of configuration class (here config)
})
.catch(err => {
console.log('Failed to load JSON configuration file.', err);
process.exit(1);
});
// 2) the second choice (using auto-implemented method based on provider name. The format is loadProviderName);
config.loadJson('path-to-json-file', {}) // second parameter is JSON parser options
.then(cfg => {
// cfg refers to the main instance of configuration class (here config)
})
.catch(err => {
console.log('Failed to load JSON configuration file.', err);
process.exit(1);
});
// A simple way to apply configuration using your own order is the code below.
const Async = require('async');
Async.waterfall(
[
function createConfigurationInstance(cb) {
const config = new Config();
return cb(null, config);
},
function loadJson(config, cb) {
config.loadJson('config.json')
.then(() => cb(null, config))
.catch(cb);
},
function loadJsonEnvironment(config, cb) {
config.loadJson('config.development.json')
.then(() => cb(null, config))
.catch(cb);
},
function loadEnvVars(config, cb) {
config.loadEnv('APP_NAME_')
.then(() => cb(null, config))
.catch(cb);
},
function loadArgs(config, cb) {
config.loadArgs()
.then(() => cb(null, config))
.catch(cb);
},
function loadReadOnlyParams(config, cb) {
config.loadObj({
appName: 'my-app-name',
readonlyProp: 'you-cant-change-it\'s-value'
})
.then(() => cb(null, config))
.catch(cb);
},
],
(err, config) {
if(err) {
console.log('Failed to load configuration', err);
process.exit(1);
}
// Here's the config object
}
);
And you're good to go!
License
MIT