steplix-config
Version:
Steplix Config is a Node.js configuration helper.
65 lines (53 loc) • 1.41 kB
JavaScript
;
const _ = require('lodash');
const rd = require('require-directory');
const dotenv = require('dotenv');
// Initialize configuration with .env file.
dotenv.config();
const env = process.env.NODE_ENV || 'production';
const separator = process.env.CONFIG_SEPARATOR || '.';
const isPrivate = ['true', '1'].includes(process.env.CONFIG_PRIVATE || false);
const objectConfig = {};
/**
* Read config with _.get strategy
*/
function config (key, defaultValue, options = {}) {
options = options || {};
let value = _.get(objectConfig, `${env}${options.separator || separator}${key}`);
if (_.isUndefined(value)) {
value = _.get(objectConfig, key, defaultValue);
}
return value;
}
/**
* Extend current config with other object.
*/
config.extend = function (source) {
_.merge(objectConfig, source);
return config;
};
/**
* Require all files in a directory.
*/
config.require = function (/* module */ m, dirname, options) {
return config.extend(rd(m, dirname, options));
};
/**
* Define separator property
*/
Object.defineProperty(config, 'separator', {
get: function () {
return separator;
}
});
if (!isPrivate) {
/**
* Define raw property, only if config is public
*/
Object.defineProperty(config, 'raw', {
get: function () {
return objectConfig;
}
});
}
module.exports = config;