use-config/src/config.ts

128 lines
3.0 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import JSON5 from 'json5';
import fs from 'fs';
import path from 'path';
// 配置类型
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;
};
[key: string]: any;
};
export const initConfig: Config = {
port: 3000,
};
export const fileIsExist = (path: string) => {
try {
fs.accessSync(path, fs.constants.F_OK);
return true;
} catch (e) {
return false;
}
};
export const getDirname = () => {
return path.resolve();
};
export const getConfigFile = (fileName = 'app.config.json5') => {
const dirname = getDirname();
// 本级
const benPath = dirname + '/' + fileName;
const ben = fileIsExist(benPath);
if (ben) return benPath;
// 上级
const lastPath = path.join(dirname, '../' + fileName);
const last = fileIsExist(lastPath);
if (last) return lastPath;
// 上上级
const lastLastPath = path.join(dirname, '../../' + fileName);
const lastLast = fileIsExist(lastLastPath);
if (lastLast) return lastLastPath;
return '';
};
// 初始化读取配置文件
export const init = (initConfigBase?: any): Config => {
const dirname = getDirname();
try {
// 配置读取路径3级判断
const filePath = getConfigFile();
console.log('config pathname:', filePath);
if (!filePath) {
throw new Error('未找到配置文件');
}
const configString = fs.readFileSync(filePath, {
encoding: 'utf-8',
});
const value = JSON5.parse(configString);
return value;
} catch (e) {
const root = dirname + '/app.config.json5';
if (!fileIsExist(root)) {
fs.writeFileSync(root, JSON5.stringify(initConfigBase || initConfig, null, 2), {
encoding: 'utf8',
});
}
console.error('未找到配置文件,初始化配置', root);
// console.error('error', e);
return initConfig;
}
};
/**
* 从全局获取
* @param initConfig 在全局未找到配置时,初始化配置的内容
*
* @returns Config
*/
export const useConfig = <T>(initConfig?: any): Config & T => {
const config = (global as any).config;
const _config = config || init(initConfig);
!config && ((global as any)['config'] = _config);
return _config;
};
export const useContext = (key: string, value: any): any => {
const _context = global as any;
if (key && value) {
_context[key] = value;
return _context;
}
if (key) {
return _context[key];
}
return _context;
};
export const deleteContext = (key: string): any => {
const _context = global as any;
if (key && _context[key]) {
delete _context[key];
return _context;
}
return _context;
};