@creditkarma/dynamic-config
Version:
Dynamic Config for Node.js backed by Consul and Vault
77 lines • 2.9 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.ConfigLoader = void 0;
const path = require("path");
const errors_1 = require("./errors");
const constants_1 = require("./constants");
const utils_1 = require("./utils");
const logger_1 = require("./logger");
function getConfigPath(sourceDir) {
const configPath = utils_1.FileUtils.findDir(sourceDir, constants_1.CONFIG_SEARCH_PATHS);
if (configPath !== null) {
return configPath;
}
else {
throw new Error('No local config directory found');
}
}
async function loadFileWithName(loaders, configPath, name) {
return utils_1.PromiseUtils.some(loaders.map((loader) => {
const types = Array.isArray(loader.type)
? loader.type
: [loader.type];
return utils_1.PromiseUtils.some(types.map((ext) => {
const filePath = path.resolve(configPath, `${name}.${ext}`);
return utils_1.FileUtils.fileExists(filePath).then(() => {
return loader.load(filePath);
});
})).then((val) => {
return val.reduce((acc, next) => {
return utils_1.ObjectUtils.overlayObjects(acc, next);
}, {});
});
})).then((configs) => {
return utils_1.PromiseUtils.resolveObjectPromises(utils_1.ObjectUtils.overlayObjects(...configs));
});
}
class ConfigLoader {
constructor({ loaders = [], configPath = utils_1.Utils.readFirstMatch(constants_1.CONFIG_PATH, constants_1.NODE_CONFIG_DIR) ||
constants_1.DEFAULT_CONFIG_PATH, configEnv = process.env.NODE_ENV || constants_1.DEFAULT_ENVIRONMENT, } = {}) {
this.loaders = loaders;
this.configPath = getConfigPath(configPath);
this.configEnv = configEnv;
}
/**
* Loads default JSON config file. This is required.
*/
async loadDefault() {
return loadFileWithName(this.loaders, this.configPath, 'default').then((config) => {
return {
name: 'default',
config,
};
}, (err) => {
logger_1.defaultLogger.error(`Unable to load default config at path[${this.configPath}]`);
throw new errors_1.DynamicConfigMissingDefault(this.configPath);
});
}
/**
* Loads JSON config file based on NODE_ENV.
*/
async loadEnvironment() {
return loadFileWithName(this.loaders, this.configPath, this.configEnv).then((config) => {
return {
name: this.configEnv,
config,
};
}, (err) => {
logger_1.defaultLogger.warn(`Unable to load config for environment[${this.configEnv}]`);
return {
name: this.configEnv,
config: {},
};
});
}
}
exports.ConfigLoader = ConfigLoader;
//# sourceMappingURL=ConfigLoader.js.map