@ljobse/appsettings-loader
Version:
This allows you to automatically map environment variables typed into your application.
76 lines • 3.04 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.applyEnvConfig = void 0;
var flattenObject = function (obj, prefix) {
if (prefix === void 0) { prefix = ""; }
return Object.keys(obj).reduce(function (acc, k) {
var pre = prefix.length ? prefix + "." : "";
if (Array.isArray(obj[k])) {
acc[pre + k] = obj[k];
}
else if (typeof obj[k] === "object")
Object.assign(acc, flattenObject(obj[k], pre + k));
else
acc[pre + k] = obj[k];
return acc;
}, {});
};
var unflatten = function (data) {
var result = {};
for (var i in data) {
var keys = i.split(".");
keys.reduce(function (res, key, j) {
return res[key] ||
(res[key] = isNaN(Number(keys[j + 1]))
? keys.length - 1 === j
? data[i]
: {}
: []);
}, result);
}
return result;
};
/**
* Function to apply the environment variables onto your config object.
* Matches the keys of the envVars with the config case insensitive, omits underscores `_` and matches nested objects in the config with dot separated keys in the envVars.
* When dot notation in env is not available this can be done by a double underscore `__`.
*
* @param appSettings Imported json settings. A typed object with default or placeholder values
* @param envVars Optional param to provide a custom list of environment variables. `process.env` by default.
* @returns An object of the same type as the appSettings param where the values are replaced with the matching values of envVars.
*/
var applyEnvConfig = function (appSettings, envVars) {
if (envVars === void 0) { envVars = process.env; }
var flattenedSettings = flattenObject(appSettings);
var env = Object.keys(envVars).reduce(function (res, itemKey) {
res[itemKey
.toLowerCase()
.replace(new RegExp("__", "g"), ".")
.replace(new RegExp("_", "g"), "")
.trim()] = envVars[itemKey];
return res;
}, {});
Object.keys(flattenedSettings).forEach(function (key) {
var envKey = key
.toLowerCase()
.replace(new RegExp("__", "g"), ".")
.replace(new RegExp("_", "g"), "")
.trim();
if (!(envKey in env))
return;
var oldValue = flattenedSettings[key];
var oldCtor = oldValue.constructor;
var newValue = env[envKey];
flattenedSettings[key] =
typeof oldValue === "boolean"
? oldCtor(newValue) &&
newValue.toString().toLowerCase() === true.toString()
: typeof oldValue === "object"
? JSON.parse(newValue)
: oldCtor(newValue);
});
var newSettings = unflatten(flattenedSettings);
return newSettings;
};
exports.applyEnvConfig = applyEnvConfig;
//# sourceMappingURL=applyEnvConfig.js.map