menuApiCache.js
2.47 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
/**
* @file 首页菜单异步 Provider 用 API 缓存(in-flight + TTL)
* 精品 / 权益共用;切店时由 invalidateMenuAndApiCaches 清空。
*/
import { invalidateSharedMenuApiCaches } from './invalidateMenuApiCaches.js'
const CACHE_TTL_MS = 60 * 1000
const cache = new Map()
const pending = new Map()
/** 清空菜单 API 内存缓存(不含 isNeed gate) */
export function clearMenuApiCache() {
cache.clear()
pending.clear()
}
/**
* 切店等场景:菜单 API 缓存 + 共用 isNeed 缓存一并失效
*/
export function invalidateMenuAndApiCaches() {
clearMenuApiCache()
invalidateSharedMenuApiCaches()
}
function cacheKey(prefix, id) {
return `${prefix}:${id == null ? '' : String(id)}`
}
function readCache(key) {
const entry = cache.get(key)
if (!entry) return null
if (Date.now() - entry.ts > CACHE_TTL_MS) {
cache.delete(key)
return null
}
return entry.value
}
function writeCache(key, value) {
cache.set(key, { value, ts: Date.now() })
}
async function cachedCall(key, fn) {
const cached = readCache(key)
if (cached !== null) return cached
if (pending.has(key)) return pending.get(key)
const promise = Promise.resolve()
.then(fn)
.then(res => {
writeCache(key, res)
return res
})
.finally(() => {
pending.delete(key)
})
pending.set(key, promise)
return promise
}
/**
* 工资申诉入口:has.performance.config.formerchant
* @param {Object} api - 含 hasPerformanceConfig 方法
* @param {string} [merchantId]
*/
export function cachedHasPerformanceConfig(api, merchantId) {
const key = cacheKey('hasPerformanceConfig', merchantId || '')
return cachedCall(key, () =>
api.hasPerformanceConfig({ merchantId: merchantId || '' })
)
}
/**
* 接待缺失:resident.direct.sale.merchant
* @param {Object} api - 含 checkMerchantDirect 方法
* @param {{ merchantId: string, scene: number }} params
*/
export function cachedCheckMerchantDirect(api, params) {
const key = cacheKey(
'checkMerchantDirect',
`${params?.merchantId || ''}|${params?.scene ?? ''}`
)
return cachedCall(key, () => api.checkMerchantDirect(params))
}
/**
* 驻店目标:staffTargetCheck.getTargetCheck
* @param {Object} api - 含 getStaffTargetTaskApi 方法
* @param {{ merchantId: string, sceneType: number }} params
*/
export function cachedGetStaffTargetTask(api, params) {
const key = cacheKey(
'getStaffTargetTask',
`${params?.merchantId || ''}|${params?.sceneType ?? ''}`
)
return cachedCall(key, () => api.getStaffTargetTaskApi(params))
}