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

View File

@ -4,39 +4,33 @@ import dotenv from 'dotenv';
// 配置类型
export type Config = {
port: number;
tokenSecret?: string;
redis?: {
host?: string;
port?: number;
password?: string;
version?: string;
[key: string]: any;
};
posgtres?: {
host?: string;
port?: number;
user?: string;
password?: string;
database?: string;
[key: string]: any;
};
minio?: {
endPoint?: string;
bucketName?: string;
useSSL?: boolean;
accessKey?: string;
secretKey?: string;
[key: string]: any;
};
mongo?: {
uri?: string;
[key: string]: any;
};
PORT: number;
// redis
REDIS_HOST?: string;
REDIS_PORT?: number;
REDIS_PASSWORD?: string;
REDIS_VERSION?: string;
REDIS_DB?: number;
REDIS_USER?: string;
// postgres
POSTGRES_HOST?: string;
POSTGRES_PORT?: number;
POSTGRES_PASSWORD?: string;
POSTGRES_USER?: string;
POSTGRES_DB?: string;
// minio
MINIO_ENDPOINT?: string;
MINIO_BUCKET_NAME?: string;
MINIO_ACCESS_KEY?: string;
MINIO_SECRET_KEY?: string;
MINIO_USE_SSL?: boolean;
// mongo
MONGO_URI?: string;
//
[key: string]: any;
};
export const initConfig: Config = {
port: 3000,
PORT: 3000,
};
export const fileIsExist = (path: string) => {
try {
@ -49,9 +43,21 @@ export const fileIsExist = (path: string) => {
export const getDirname = () => {
return process.cwd();
};
type ConfigOpts = {
/**
*
*/
export type ConfigOpts = {
/**
* , default: process.cwd() + envConfigFile
*/
envConfigFile?: string;
/**
* , default: process.cwd()
*/
cwd?: string;
/**
* , default: .env
*/
fileName?: string;
};
/**
@ -82,9 +88,17 @@ export const getConfigFile = (opts?: ConfigOpts) => {
if (lastLast) return lastLastPath;
return '';
};
// 初始化读取配置文件
export const init = (opts?: ConfigOpts & { dotenvOpts?: dotenv.DotenvConfigOptions }): Config => {
type GetConfigOpts = ConfigOpts & { dotenvOpts?: dotenv.DotenvConfigOptions };
/**
* ,
* @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) {
const prased = dotenv.config(opts.dotenvOpts).parsed as Config;
if (prased) {
@ -109,13 +123,28 @@ export const init = (opts?: ConfigOpts & { dotenvOpts?: dotenv.DotenvConfigOptio
*
* @returns Config
*/
export const useConfig = <T>(): Config & T => {
export const useConfig = <T>(onlyInitConfig?: GetConfigOpts): Config & T => {
const config = (global as any).config;
const _config = config || init();
const _config = config || getConfig(onlyInitConfig);
!config && ((global as any)['config'] = _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 => {
let v = useConfig()[key];
if (!v) {
@ -124,11 +153,46 @@ export const useKey = (key: string, opts?: { defaultValue?: string; isNumber?: b
if (!v) {
return opts?.defaultValue || null;
}
if (opts?.isNumber) {
if (opts?.isNumber && typeof v === 'string') {
return Number(v);
}
if (opts?.isBoolean) {
if (opts?.isBoolean && typeof v === 'string') {
return v === 'true';
}
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 {};
}
};