typed-environment-loader
Version:
typed-environment-loader is a lightweight utility for loading environment variables in a typed manner, ensuring type safety and consistency in your Node.js applications.
134 lines (133 loc) • 6.18 kB
JavaScript
"use strict";
var __values = (this && this.__values) || function(o) {
var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
if (m) return m.call(o);
if (o && typeof o.length === "number") return {
next: function () {
if (o && i >= o.length) o = void 0;
return { value: o && o[i++], done: !o };
}
};
throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
};
var __read = (this && this.__read) || function (o, n) {
var m = typeof Symbol === "function" && o[Symbol.iterator];
if (!m) return o;
var i = m.call(o), r, ar = [], e;
try {
while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
}
catch (error) { e = { error: error }; }
finally {
try {
if (r && !r.done && (m = i["return"])) m.call(i);
}
finally { if (e) throw e.error; }
}
return ar;
};
var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
if (ar || !(i in from)) {
if (!ar) ar = Array.prototype.slice.call(from, 0, i);
ar[i] = from[i];
}
}
return to.concat(ar || Array.prototype.slice.call(from));
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.EnvironmentLoader = void 0;
var debug_1 = require("./debug");
var errors_1 = require("./errors");
var parser_registry_1 = require("./parsers/parser-registry");
var EnvironmentLoader = (function () {
function EnvironmentLoader(_schema, _env, config) {
if (_env === void 0) { _env = process.env; }
if (config === void 0) { config = {}; }
var _this = this;
var _a;
this._schema = _schema;
this._env = _env;
this._debug = (0, debug_1.createDebugLogger)(this.constructor.name);
this._parser = new parser_registry_1.ParserRegistry();
this._config = {
separator: config.separator || '__',
prefix: config.prefix || '',
transformEnvKey: config.transformEnvKey || (function (key) { return key.toUpperCase(); }),
transformPath: config.transformPath || (function (path) { return path.join(_this._config.separator); }),
defaultRequired: (_a = config.defaultRequired) !== null && _a !== void 0 ? _a : false
};
}
EnvironmentLoader.prototype.load = function () {
var e_1, _a;
this._debug.info('Starting to load environment variables');
var result = {};
var stack = [{ schema: this._schema, result: result, path: [] }];
while (stack.length > 0) {
var current = stack.pop();
this._debug.info('Processing schema', current.schema, 'at path', current.path);
var entries = Object.entries(current.schema).reverse();
try {
for (var entries_1 = (e_1 = void 0, __values(entries)), entries_1_1 = entries_1.next(); !entries_1_1.done; entries_1_1 = entries_1.next()) {
var _b = __read(entries_1_1.value, 2), key = _b[0], config = _b[1];
var currentPath = __spreadArray(__spreadArray([], __read(current.path), false), [key], false);
var envKey = this.getEnvKey(config, currentPath);
this._debug.info('Processing key', key, 'with config', config, 'and envKey', envKey);
if (this.isSchemaItem(config)) {
current.result[key] = this.parseValue(config, currentPath, envKey);
}
else {
var nestedResult = {};
current.result[key] = nestedResult;
stack.push({
schema: config,
result: nestedResult,
path: currentPath
});
}
}
}
catch (e_1_1) { e_1 = { error: e_1_1 }; }
finally {
try {
if (entries_1_1 && !entries_1_1.done && (_a = entries_1.return)) _a.call(entries_1);
}
finally { if (e_1) throw e_1.error; }
}
}
this._debug.info('Finished loading environment variables');
return result;
};
EnvironmentLoader.prototype.parseValue = function (schema, path, envKey) {
var _a, _b;
this._debug.info('Parsing value for envKey', envKey, 'at path', path);
var envKeyTransformed = this._config.transformEnvKey(envKey);
var value = (_a = this._env[envKeyTransformed]) === null || _a === void 0 ? void 0 : _a.trim();
if (!value) {
this._debug.warn('Value for envKey', envKey, 'is missing');
var isRequired = (_b = schema.required) !== null && _b !== void 0 ? _b : this._config.defaultRequired;
if (isRequired) {
this._debug.warn('envKey', envKey, 'is required but missing, throwing error');
throw new errors_1.EnvironmentMissingError(envKey, path);
}
this._debug.info('Using default value for envKey', envKey);
return this.handleDefault(schema.default);
}
this._debug.info('Parsing value', value, 'for envKey', envKey);
return this._parser.parse({ envKey: envKey, path: path, schema: schema, value: value }).value;
};
EnvironmentLoader.prototype.getEnvKey = function (config, path) {
if ('name' in config && config.name) {
return this._config.prefix + config.name;
}
return this._config.prefix + this._config.transformPath(path);
};
EnvironmentLoader.prototype.handleDefault = function (defaultValue) {
return Array.isArray(defaultValue) ? __spreadArray([], __read(defaultValue), false) : defaultValue;
};
EnvironmentLoader.prototype.isSchemaItem = function (value) {
return 'type' in value;
};
return EnvironmentLoader;
}());
exports.EnvironmentLoader = EnvironmentLoader;