perf: 优化配置

This commit is contained in:
熊潇 2025-04-18 23:08:23 +08:00
parent 0cc5c0f98e
commit 748aef5f79
2 changed files with 108 additions and 44 deletions

View File

@ -1,6 +1,6 @@
{ {
"name": "@kevisual/use-config", "name": "@kevisual/use-config",
"version": "1.0.10", "version": "1.0.11",
"types": "dist/config.d.ts", "types": "dist/config.d.ts",
"scripts": { "scripts": {
"build": "npm run clean && tsup", "build": "npm run clean && tsup",
@ -20,13 +20,13 @@
"license": "UNLICENSED", "license": "UNLICENSED",
"type": "module", "type": "module",
"devDependencies": { "devDependencies": {
"@types/node": "^22.13.5", "@types/node": "^22.14.1",
"dotenv": "^16.4.7", "dotenv": "^16.5.0",
"fast-glob": "^3.3.2", "fast-glob": "^3.3.3",
"json-schema-to-ts": "^3.1.1", "json-schema-to-ts": "^3.1.1",
"json5": "^2.2.3", "json5": "^2.2.3",
"tsup": "^8.4.0", "tsup": "^8.4.0",
"typescript": "^5.7.3" "typescript": "^5.8.3"
}, },
"exports": { "exports": {
".": { ".": {
@ -54,6 +54,6 @@
"dotenv": "^16.4.7" "dotenv": "^16.4.7"
}, },
"dependencies": { "dependencies": {
"@kevisual/load": "^0.0.4" "@kevisual/load": "^0.0.6"
} }
} }

View File

@ -4,39 +4,33 @@ import dotenv from 'dotenv';
// 配置类型 // 配置类型
export type Config = { export type Config = {
port: number; PORT: number;
tokenSecret?: string; // redis
redis?: { REDIS_HOST?: string;
host?: string; REDIS_PORT?: number;
port?: number; REDIS_PASSWORD?: string;
password?: string; REDIS_VERSION?: string;
version?: string; REDIS_DB?: number;
[key: string]: any; REDIS_USER?: string;
}; // postgres
posgtres?: { POSTGRES_HOST?: string;
host?: string; POSTGRES_PORT?: number;
port?: number; POSTGRES_PASSWORD?: string;
user?: string; POSTGRES_USER?: string;
password?: string; POSTGRES_DB?: string;
database?: string; // minio
[key: string]: any; MINIO_ENDPOINT?: string;
}; MINIO_BUCKET_NAME?: string;
minio?: { MINIO_ACCESS_KEY?: string;
endPoint?: string; MINIO_SECRET_KEY?: string;
bucketName?: string; MINIO_USE_SSL?: boolean;
useSSL?: boolean; // mongo
accessKey?: string; MONGO_URI?: string;
secretKey?: string; //
[key: string]: any;
};
mongo?: {
uri?: string;
[key: string]: any;
};
[key: string]: any; [key: string]: any;
}; };
export const initConfig: Config = { export const initConfig: Config = {
port: 3000, PORT: 3000,
}; };
export const fileIsExist = (path: string) => { export const fileIsExist = (path: string) => {
try { try {
@ -49,9 +43,21 @@ export const fileIsExist = (path: string) => {
export const getDirname = () => { export const getDirname = () => {
return process.cwd(); return process.cwd();
}; };
type ConfigOpts = { /**
*
*/
export type ConfigOpts = {
/**
* , default: process.cwd() + envConfigFile
*/
envConfigFile?: string; envConfigFile?: string;
/**
* , default: process.cwd()
*/
cwd?: string; cwd?: string;
/**
* , default: .env
*/
fileName?: string; fileName?: string;
}; };
/** /**
@ -82,9 +88,17 @@ export const getConfigFile = (opts?: ConfigOpts) => {
if (lastLast) return lastLastPath; if (lastLast) return lastLastPath;
return ''; return '';
}; };
type GetConfigOpts = ConfigOpts & { dotenvOpts?: dotenv.DotenvConfigOptions };
// 初始化读取配置文件 /**
export const init = (opts?: ConfigOpts & { dotenvOpts?: dotenv.DotenvConfigOptions }): Config => { * ,
* @param opts
* @param opts.envConfigFile , default: process.cwd() + envConfigFile
* @param opts.cwd , default: process.cwd()
* @param opts.fileName , default: .env
* @param opts.dotenvOpts dotenv配置选项
* @returns
*/
export const getConfig = (opts?: GetConfigOpts): Config => {
if (opts?.dotenvOpts) { if (opts?.dotenvOpts) {
const prased = dotenv.config(opts.dotenvOpts).parsed as Config; const prased = dotenv.config(opts.dotenvOpts).parsed as Config;
if (prased) { if (prased) {
@ -109,13 +123,28 @@ export const init = (opts?: ConfigOpts & { dotenvOpts?: dotenv.DotenvConfigOptio
* *
* @returns Config * @returns Config
*/ */
export const useConfig = <T>(): Config & T => { export const useConfig = <T>(onlyInitConfig?: GetConfigOpts): Config & T => {
const config = (global as any).config; const config = (global as any).config;
const _config = config || init(); const _config = config || getConfig(onlyInitConfig);
!config && ((global as any)['config'] = _config); !config && ((global as any)['config'] = _config);
return _config; return _config;
}; };
/**
*
* @param configOpts
* @param opts
* @param opts.cwd , default: process.cwd()
* @param opts.fileName , default: config.json
*/
export const updateConfig = (configOpts: GetConfigOpts) => {
const _config = (global as any).config || {};
const newConfig = getConfig(configOpts);
Object.assign(_config, newConfig);
(global as any).config = _config;
return _config;
};
export const useKey = (key: string, opts?: { defaultValue?: string; isNumber?: boolean; isBoolean?: boolean }): string | number | boolean => { export const useKey = (key: string, opts?: { defaultValue?: string; isNumber?: boolean; isBoolean?: boolean }): string | number | boolean => {
let v = useConfig()[key]; let v = useConfig()[key];
if (!v) { if (!v) {
@ -124,11 +153,46 @@ export const useKey = (key: string, opts?: { defaultValue?: string; isNumber?: b
if (!v) { if (!v) {
return opts?.defaultValue || null; return opts?.defaultValue || null;
} }
if (opts?.isNumber) { if (opts?.isNumber && typeof v === 'string') {
return Number(v); return Number(v);
} }
if (opts?.isBoolean) { if (opts?.isBoolean && typeof v === 'string') {
return v === 'true'; return v === 'true';
} }
return v; return v;
}; };
/**
* json配置文件
* @param config
* @param opts
* @param opts.cwd , default: process.cwd()
* @param opts.fileName , default: config.json
*/
export const writeJsonConfig = (config = {}, opts?: Omit<ConfigOpts, 'envConfigFile'>) => {
const filePath = getConfigFile({ ...opts, fileName: opts?.fileName || 'config.json' });
if (!filePath) {
throw new Error(`未找到配置文件: ${opts?.fileName || 'config.json'}`);
}
fs.writeFileSync(filePath, JSON.stringify(config, null, 2));
};
/**
* json配置文件
* @param opts
* @param opts.cwd , default: process.cwd()
* @param opts.fileName , default: config.json
* @returns
*/
export const readJsonConfig = (opts?: Omit<ConfigOpts, 'envConfigFile'>) => {
const filePath = getConfigFile({ ...opts, fileName: opts?.fileName || 'config.json' });
if (!filePath) {
throw new Error(`未找到配置文件: ${opts?.fileName || 'config.json'}`);
}
try {
const value = JSON.parse(fs.readFileSync(filePath, 'utf-8'));
return value;
} catch (e) {
return {};
}
};