@placeholdersoft/typed-env
Version:
typed-env can help us better handle environment variables
57 lines (56 loc) • 1.64 kB
JavaScript
Object.defineProperty(exports, "__esModule", { value: true });
exports.EnvBox = void 0;
class EnvBox {
constructor(name, value) {
this.name = name;
this.value = value;
}
required() {
if (this.value == null) {
throw new Error(`Required env variable for name: ${this.name} is not set`);
}
return new EnvBox(this.name, this.value);
}
optional() {
return new EnvBox(this.name, this.value);
}
default(value) {
var _a;
return new EnvBox(this.name, (_a = this.value) !== null && _a !== void 0 ? _a : value);
}
nonEmpty() {
if (this.value == null || this.value === '') {
throw new Error(`Env variable for name: ${this.name} is empty`);
}
return new EnvBox(this.name, this.value);
}
toBoolean() {
const value = this.value;
if (value === 'true' || value === 'TRUE') {
return true;
}
if (value === 'false' || value === 'FALSE') {
return false;
}
throw new Error(`Env variable for name: ${this.name} is not boolean, value: ${value}`);
}
toInt(radix) {
const value = this.toString();
if (value == null) {
return undefined;
}
const val = parseInt(value, radix);
if (isNaN(val)) {
throw new Error(`Env variable for name: ${this.name} is not an integer`);
}
return val;
}
toString() {
return this.value;
}
static of(name, env) {
return new EnvBox(name, env[name]);
}
}
exports.EnvBox = EnvBox;
;