fix: add context

This commit is contained in:
熊潇 2024-11-27 19:53:32 +08:00
parent 3288b64dbf
commit a2678606a2
4 changed files with 61 additions and 4 deletions

View File

@ -1,13 +1,12 @@
{
"name": "@kevisual/use-config",
"version": "1.0.2",
"version": "1.0.3",
"types": "dist/config.d.ts",
"scripts": {
"build": "npm run clean && rollup -c",
"watch": " rollup -c -w",
"clean": "rimraf dist"
},
"publishConfig": {
"access": "public"
},
@ -49,6 +48,10 @@
"./pkgs": {
"import": "./dist/pkgs.mjs",
"types": "./dist/pkgs.d.ts"
},
"./context": {
"import": "./dist/context.mjs",
"types": "./dist/context.d.ts"
}
}
}

View File

@ -49,4 +49,25 @@ export default [
},
plugins: [dts()],
},
{
input: 'src/context.ts', // TypeScript 入口文件
output: {
file: 'dist/context.mjs', // 输出文件
format: 'es', // 输出格式设置为 ES 模块
},
plugins: [
resolve(), // 使用 @rollup/plugin-node-resolve 解析 node_modules 中的模块
commonjs(),
typescript(), // 使用 @rollup/plugin-typescript 处理 TypeScript 文件
],
external: [],
},
{
input: 'src/context.ts',
output: {
file: 'dist/context.d.ts',
format: 'es',
},
plugins: [dts()],
},
];

View File

@ -106,7 +106,7 @@ export const useConfig = <T>(initConfig?: any): Config & T => {
return _config;
};
export const useContext = (key: string, value: any): any => {
export const useConfigContext = (key: string, value: any): any => {
const _context = global as any;
if (key && value) {
_context[key] = value;
@ -117,7 +117,7 @@ export const useContext = (key: string, value: any): any => {
}
return _context;
};
export const deleteContext = (key: string): any => {
export const deleteConfigContext = (key: string): any => {
const _context = global as any;
if (key && _context[key]) {
delete _context[key];

33
src/context.ts Normal file
View File

@ -0,0 +1,33 @@
type GlobalContext = {
redis?: any;
};
export const useContext = (initContext?: GlobalContext) => {
const context: GlobalContext = (global as any).context;
const _context = context || initContext;
!context && ((global as any)['context'] = _context);
return _context;
};
export const useContextKey = <T>(key: string, init: () => T): T => {
const _context = useContext();
if (key && init) {
_context[key] = init();
return _context[key] as any;
}
if (key) {
return _context[key];
}
return _context as any;
};
export const useContextKeySync = async <T = any>(key: string, init: () => Promise<T>): Promise<T> => {
const _context = useContext({});
if (key && init) {
_context[key] = await init();
return _context[key] as any;
}
if (key) {
return _context[key];
}
return _context as any;
};