import { setGlobalStorage, getGlobalStorage } from '@/native/api/storage'; export async function executeAndCache( cacheKey: string, executor: () => Promise, options: { storageKeyPrefix?: string; } = {} ): Promise { const { storageKeyPrefix = 'joli_cache_' } = options; const storageKey = storageKeyPrefix + cacheKey; const timestampKey = storageKey + '_timestamp'; try { const data = await executor(); const timestamp = Date.now(); // 执行后直接缓存结果 try { if (data !== null && data !== undefined) { await setGlobalStorage(storageKey, data); await setGlobalStorage(timestampKey, timestamp.toString()); console.log('[Cache] Cached result for key:', cacheKey); } } catch (error) { console.warn('[Cache] Failed to save to localStorage for key:', cacheKey, error); } return data; } catch (error) { console.warn('[Cache] Executor failed for key:', cacheKey, error); throw error; } } export async function executeWithPersistentCache( cacheKey: string, executor: () => Promise, options: { cacheDuration?: number; storageKeyPrefix?: string; } = {} ): Promise { const { cacheDuration = -1, // 永不过期 storageKeyPrefix = 'joli_cache_' } = options; const storageKey = storageKeyPrefix + cacheKey; const timestampKey = storageKey + '_timestamp'; const neverExpires = cacheDuration === Infinity || cacheDuration === -1; // 1. 先尝试从 localStorage 读取数据 try { const { data: dataStr } = await getGlobalStorage(storageKey); const { data: timestampStr } = await getGlobalStorage(timestampKey); if (dataStr && timestampStr) { const timestamp = parseInt(timestampStr, 10); if (neverExpires || Date.now() - timestamp < cacheDuration) { console.log('[Cache] Using localStorage cached data for key:', cacheKey); const data = JSON.parse(dataStr); // 如果不是永不过期,后台异步更新缓存(不阻塞返回) if (!neverExpires) { setTimeout(async () => { try { console.log('[Cache] Background updating cache for key:', cacheKey); const freshData = await executor(); const newTimestamp = Date.now(); await setGlobalStorage(storageKey, freshData); await setGlobalStorage(timestampKey, newTimestamp.toString()); console.log('[Cache] Background cache update completed for key:', cacheKey); } catch (error) { console.warn('[Cache] Background cache update failed for key:', cacheKey, error); } }, 0); } return data; } else { await setGlobalStorage(storageKey, null); await setGlobalStorage(timestampKey, null); } } } catch (error) { console.warn('[Cache] Failed to read from localStorage for key:', cacheKey, error); } try { const data = await executor(); const timestamp = Date.now(); // 保存到 localStorage try { if (data) { await setGlobalStorage(storageKey, data); await setGlobalStorage(timestampKey, timestamp.toString()); } } catch (error) { console.warn('[Cache] Failed to save to localStorage for key:', cacheKey, error); } return data; } catch (error) { console.warn('[Cache] Executor failed for key:', cacheKey, error); throw error; } }