cache for store chard
This commit is contained in:
@@ -0,0 +1,51 @@
|
||||
const STORE_CHART_CACHE_TTL = 5 * 60 * 1000;
|
||||
|
||||
type StoreChartCacheEntry = {
|
||||
data?: unknown;
|
||||
cachedAt: number;
|
||||
pending?: Promise<unknown>;
|
||||
};
|
||||
|
||||
const cache = new Map<string, StoreChartCacheEntry>();
|
||||
let cacheGeneration = 0;
|
||||
|
||||
/** 缓存门店图表请求结果,并合并同一数据的并发请求。 */
|
||||
export async function getStoreChartCache<T>(key: string, loader: () => Promise<T>): Promise<T> {
|
||||
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();
|
||||
}
|
||||
Reference in New Issue
Block a user