This commit is contained in:
2026-01-13 01:31:24 +08:00
parent 4c3be1a4a4
commit bd0eb4e791

View File

@@ -5,7 +5,7 @@ import { fileURLToPath } from 'url';
// 配置类型
export type Config<T = {}> = {
PORT: string;
PORT?: string;
// redis
REDIS_HOST?: string;
REDIS_PORT?: string;
@@ -70,6 +70,10 @@ export type Config<T = {}> = {
POCKETBASE_URL?: string;
POCKETBASE_TOKEN?: string;
CNB_TOKEN?: string;
CNB_COOKIE?: string;
KUBECONFIG_DATA?: string;
// 其他自定义配置
[key: string]: any;
} & T;
@@ -132,7 +136,7 @@ export const getConfigFile = (opts?: ConfigOpts) => {
if (lastLast) return lastLastPath;
return '';
};
type GetConfigOpts = ConfigOpts & { dotenvOpts?: dotenv.DotenvConfigOptions, quite?: boolean };
type GetConfigOpts = ConfigOpts & { dotenvOpts?: dotenv.DotenvConfigOptions, quite?: boolean, showError?: boolean };
/**
* 初始化配置, 不会把配置内容挂载到全局
* @param opts 配置选项
@@ -144,22 +148,35 @@ type GetConfigOpts = ConfigOpts & { dotenvOpts?: dotenv.DotenvConfigOptions, qui
*/
export const getConfig = (opts?: GetConfigOpts): Config => {
let quiet = opts?.quite ?? true;
const showError = opts?.showError ?? false;
if (opts?.dotenvOpts) {
const prased = dotenv.config({ quiet, ...opts.dotenvOpts }).parsed as Config;
if (prased) {
return prased;
} else {
if (showError) {
if(!quiet) {
console.warn('config 读取失败');
}
throw new Error('未找到配置文件');
}
return {} as Config;
}
}
// 配置读取路径3级判断
const filePath = getConfigFile(opts);
if (!quiet) {
if (!quiet && filePath) {
console.log('config pathname:', filePath);
}
if (!filePath) {
if(showError) {
if(!quiet) {
console.warn('config 路径未找到');
}
throw new Error('未找到配置文件');
}
return {} as Config;
}
const value = dotenv.config({ quiet: true, path: filePath }).parsed as Config;
return value;
};