takin
Version:
Front end engineering base toolchain and scaffold
122 lines • 3.71 kB
JavaScript
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.Environment = void 0;
const dotenv_1 = __importDefault(require("dotenv"));
const lodash_1 = require("lodash");
const logger_1 = require("./logger");
const utils_1 = require("./utils");
/**
* 环境变量支持,用于统一环境变量的获取、解析和值判断
*/
class Environment {
constructor() {
this.options = {
override: true,
falsyValues: ['', 'none', 'false', '0', 'undefined', 'null'],
arraySeparators: [',', ' ']
};
this.parsedEnv = {};
/**
* 是否已开启 env 支持
*/
this.enabled = false;
}
/**
* 开启 env 支持
*/
enable() {
this.enabled = true;
return this;
}
/**
* 关闭 env 支持
*/
disable() {
this.enabled = false;
return this;
}
/**
* 载入 .env 文件
*/
load() {
var _a;
if (!this.enabled)
return;
try {
this.parsedEnv = {
...process.env,
...(((_a = dotenv_1.default.config((0, lodash_1.omit)(this.options, ['falsyValues', 'arraySeparators']))) === null || _a === void 0 ? void 0 : _a.parsed) || {})
};
}
catch (error) {
logger_1.logger.error(`环境变量载入失败,原因: ${error}`, {
error: error
});
}
return this;
}
/**
* 是否包含某个环境变量
* @param name - 环境变量名称
* @returns 是否包含环境变量
*/
has(name) {
return this.get(name) != null;
}
/**
* 获取环境变量的值
* @param name - 环境变量名称
* @returns 环境变量的值
*/
get(name) {
var _a;
return (_a = this.parsedEnv) === null || _a === void 0 ? void 0 : _a[name];
}
/**
* 判断环境变量是否为 false,基于 falsyValues 配置
* @param name - 环境变量名称
* @returns 返回 `true` 或 `false`
*/
isFalsy(name) {
var _a;
const value = this.get(name);
if (value == null)
return false;
if ((((_a = this.options) === null || _a === void 0 ? void 0 : _a.falsyValues) || []).includes(value))
return true;
return false;
}
/**
* 判断环境变量是否为 true,基于 falsyValues 配置,当环境变量未配置时为 false
* @param name - 环境变量名称
* @returns 返回 `true` 或 `false`
*/
isTruthy(name) {
return this.has(name) && !this.isFalsy(name);
}
/**
* 将环境变量的值解析为数组并返回,基于 arraySeparators 配置
* @param name - 环境变量名称
* @returns 解析后的数组
*/
array(name) {
return this.arrayify(this.get(name));
}
/**
* 将值解析为数组,基于 arraySeparators 配置
* @param value - 需要解析的值
* @returns 解析后的数组
*/
arrayify(value) {
var _a, _b;
if (!((_b = (_a = this.options) === null || _a === void 0 ? void 0 : _a.arraySeparators) === null || _b === void 0 ? void 0 : _b.length) || value == null)
return (0, utils_1.asArray)(value);
const seperatorPattern = new RegExp(`[${this.options.arraySeparators.join('')}]+`, 'g');
return value.split(seperatorPattern);
}
}
exports.Environment = Environment;
//# sourceMappingURL=environment.js.map