const STORE_CHART_CACHE_TTL = 5 * 60 * 1000; type StoreChartCacheEntry = { data?: unknown; cachedAt: number; pending?: Promise; }; const cache = new Map(); let cacheGeneration = 0; /** 缓存门店图表请求结果,并合并同一数据的并发请求。 */ export async function getStoreChartCache(key: string, loader: () => Promise): Promise { const now = Date.now(); const entry = cache.get(key); if (entry?.data !== undefined && now - entry.cachedAt < STORE_CHART_CACHE_TTL) { return entry.data as T; } if (entry?.pending) { return await entry.pending as T; } const generation = cacheGeneration; const pending = loader(); cache.set(key, { data: entry?.data, cachedAt: entry?.cachedAt || 0, pending }); try { const data = await pending; if (generation === cacheGeneration) { cache.set(key, { data, cachedAt: Date.now() }); } return data; } catch (error) { if (cache.get(key)?.pending === pending) { cache.delete(key); } throw error; } } /** 清空门店图表缓存,并使清空前发起的请求不再回填缓存。 */ export function clearStoreChartCache(): void { cacheGeneration++; cache.clear(); }