From 213219518f4271480cce3844e2184312aae2f067 Mon Sep 17 00:00:00 2001 From: xion Date: Sat, 1 Mar 2025 17:31:13 +0800 Subject: [PATCH] =?UTF-8?q?fix:=20=E4=BC=98=E5=8C=96=E5=8A=9F=E8=83=BD?= =?UTF-8?q?=EF=BC=8C=E5=8E=BB=E6=8E=89sync=EF=BC=8C=E5=BD=93useContextKey?= =?UTF-8?q?=E4=B8=AD=E5=A6=82=E6=9E=9C=E6=9C=89promise=E8=87=AA=E5=B7=B1?= =?UTF-8?q?=E7=BB=B4=E6=8A=A4Promise?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- package.json | 5 ++++- src/context.ts | 48 ++++++++++++++++++++++++++++++++++++------------ 2 files changed, 40 insertions(+), 13 deletions(-) diff --git a/package.json b/package.json index a958330..978339d 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@kevisual/use-config", - "version": "1.0.8", + "version": "1.0.9", "types": "dist/config.d.ts", "scripts": { "build": "npm run clean && rollup -c", @@ -57,5 +57,8 @@ "import": "./dist/file-store.mjs", "types": "./dist/file-store.d.ts" } + }, + "dependencies": { + "@kevisual/load": "^0.0.4" } } \ No newline at end of file diff --git a/src/context.ts b/src/context.ts index 1998501..7cb0f73 100644 --- a/src/context.ts +++ b/src/context.ts @@ -1,3 +1,5 @@ +import { BaseLoad } from '@kevisual/load'; + type GlobalContext = { redis?: any; } & U; @@ -15,28 +17,50 @@ export const useContext = (initContext?: GlobalContext): T => return global.context; }; +/** + * 获取上下文,当key存在时,返回key对应的值,不存在时,返回init函数的值 + * 若init不存在,key存在,直接进行循环检测,直到key存在,需要await + * + * @param key + * @param init + * @returns + */ export const useContextKey = (key: string, init?: () => T): T => { const _context = useContext({}); if (key && typeof _context[key] !== 'undefined') { return _context[key]; } if (key && init) { + // 没有初始化过,初始化函数 _context[key] = (init as () => T)(); return _context[key] as any; } - return _context as any; -}; - -export const useContextKeySync = async (key: string, init?: () => Promise): Promise => { - const _context = useContext({}); - if (key && typeof _context[key] !== 'undefined') { - return _context[key]; + // 其他情况,默认已经初始化过 + if (key) { + // 加载 + const baseLoad = new BaseLoad(); + const voidFn = async () => { + return _context[key]; + }; + const checkFn = async () => { + const loadRes = await baseLoad.load(voidFn, { + key, + isReRun: true, + checkSuccess: () => _context[key], + timeout: 5 * 60 * 1000, + interval: 1000, + // + }); + if (loadRes.code !== 200) { + console.error('load key error'); + return null; + } + return _context[key]; + }; + return checkFn() as any; } - if (key && init) { - _context[key] = await init(); - return _context[key] as any; - } - return _context as any; + console.error('key is empty'); + return null; }; export const setContextKey = (key: string, value: T) => {