@nexe/config-manager
Version:
Nexe Config Manager - A flexible configuration management solution with multiple sources and hot reload support
77 lines • 2.01 kB
JavaScript
import { __decorate, __metadata } from "tslib";
import { injectable } from 'tsyringe';
/**
* 环境变量配置源
*/
let EnvironmentConfigSource = class EnvironmentConfigSource {
/**
* @param prefix 环境变量前缀,例如:'APP_'
*/
constructor(prefix = '') {
this.prefix = prefix;
}
/**
* 从环境变量加载配置
*/
async load(key, _pathPrefix) {
if (!key) {
return undefined;
}
const envKey = this.getEnvKey(key);
const value = process.env[envKey];
return this.parseValue(value);
}
/**
* 获取配置源名称
*/
getName() {
return 'EnvironmentConfigSource';
}
/**
* 环境变量配置不支持热更新
*/
supportsHotReload() {
return false;
}
/**
* 转换环境变量键名
* 将点分隔的配置键转换为下划线分隔的环境变量键
* 例如:'app.server.port' -> 'APP_SERVER_PORT'
*/
getEnvKey(key) {
return `${this.prefix}${key.replace(/\./g, '_').toUpperCase()}`;
}
/**
* 尝试解析环境变量值
*/
parseValue(value) {
if (value === undefined) {
return undefined;
}
// 尝试解析为数字
if (/^-?\d+(\.\d+)?$/.test(value)) {
return Number(value);
}
// 尝试解析为布尔值
if (value.toLowerCase() === 'true') {
return true;
}
if (value.toLowerCase() === 'false') {
return false;
}
// 尝试解析为JSON
try {
return JSON.parse(value);
}
catch {
// 如果不是JSON,则返回原始字符串
return value;
}
}
};
EnvironmentConfigSource = __decorate([
injectable(),
__metadata("design:paramtypes", [Object])
], EnvironmentConfigSource);
export { EnvironmentConfigSource };
//# sourceMappingURL=environment-config-source.js.map