@dynrl/drl-settings
Version:
Standardizes settings access
96 lines • 3.4 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
const env = require('dotenv');
const fs = require('fs');
const path = require('path');
/**
* Wrapper for accessing settings in DRL apps and modules.
*/
class DrlSettings {
/**
* Detects if importing .env files is allowed. This requires that the
* environment variable DRL_HOST_ENV be set to CI or LOCAL.
*/
static useEnvFile() {
// This is a environmental setting emitted in azure instances. Hopefully
// we can rely on it to
return process.env['DRL_HOST_ENV'] === 'CI' ||
process.env['DRL_HOST_ENV'] === 'LOCAL';
}
/**
* Initializes and validates anticipated keys.
* @param keys - A list of keys that are going to be used
* @param filePath - An optional
*/
static initSettings(keys, filePath) {
if (!keys || keys.length === 0) {
this.warn('No keys defined... This call has no effect!');
}
// Add keys to white list
keys.forEach(k => {
this.WhiteList[k] = true;
});
// When running on azure, we should rely on the app settings instead of env files.
// This ensures that the creation of app settings are intentional.
if (this.useEnvFile() && filePath) {
filePath = path.resolve(filePath);
if (!fs.existsSync(filePath)) {
throw new Error(`Could not locate .env file at ${filePath}`);
}
this.log(`Looking for .env file at ${filePath}.`);
env.config({ path: filePath });
}
// Validate that provided keys now exist in process.env
this.checkKeys(keys);
}
/**
* Lists all available keys
*/
static getSettingKeys() {
let result = new Array();
for (const key in this.WhiteList) {
if (this.WhiteList.hasOwnProperty(key) &&
process.env.hasOwnProperty(key)) {
result.push(key);
}
}
return result;
}
/**
* Grabs setting value for a given key.
* @param key - key to look up
* @throws - If key has not be properly registered or doesn't exist in process.env
*/
static getSetting(key) {
if (!this.WhiteList[key]) {
throw new Error(`Non-sanctioned key detected, ${key}. Make sure keys are registered during the initSettings call.`);
}
const val = process.env[key];
if (val == null) {
throw new Error(`Could not locate required setting, ${key}. Add this to your environment variables.`);
}
if (val === '') {
this.warn(`Empty key detected, ${key}.`);
}
return val;
}
static warn(msg) {
console.warn(`DrlSettings: ${msg}`);
}
static log(msg) {
console.log(`DrlSettings: ${msg}`);
}
static checkKeys(keys) {
keys.forEach(k => {
if (process.env[k] === void 0) {
throw new Error(`Missing key detected ${k}`);
}
if (process.env[k] === '') {
throw new Error(`Empty key detected ${k}`);
}
});
}
}
DrlSettings.WhiteList = {};
exports.DrlSettings = DrlSettings;
//# sourceMappingURL=index.js.map