dailyReportNewVersionGate.js
2.42 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
101
102
103
104
105
106
107
108
109
110
111
112
113
/**
* 三份动态表单日报首页入口显隐 — dj.api.smartcarlife.dailyReport.new.version.isNeed
*/
const CACHE_TTL_MS = 60 * 1000
const cache = new Map()
const pendingByMerchantId = new Map()
let apiClientOverride = null
let apiModule = null
/** 单测注入 mock api */
export function __setApiClientForTest(client) {
apiClientOverride = client
}
/** 单测清空缓存 */
export function clearDailyReportNewVersionCache() {
cache.clear()
pendingByMerchantId.clear()
}
function getApiClient() {
if (apiClientOverride) {
return apiClientOverride
}
if (!apiModule) {
// 小程序侧与页面一致用 require;单测通过 __setApiClientForTest 注入,不触发 require
apiModule = require('~/api/api.js')
}
return apiModule.default || apiModule
}
export function resolveShopMerchantId(userInfo = {}) {
const id =
userInfo.shopMerchantId ||
userInfo.default4SStoreInfo?.merchantId ||
userInfo.default4SStoreInfo_crowdFunding?.merchantId
if (id == null || id === '') {
return ''
}
return String(id)
}
export function parseIsNeedResponse(res = {}) {
if (res?.code != 0) {
return false
}
const data = res.data
if (data === true || data === 1) {
return true
}
if (data === 'true' || data === '1') {
return true
}
return false
}
function readCache(merchantId) {
const entry = cache.get(merchantId)
if (!entry) {
return null
}
if (Date.now() - entry.ts > CACHE_TTL_MS) {
cache.delete(merchantId)
return null
}
return entry.value
}
function writeCache(merchantId, value) {
cache.set(merchantId, { value: !!value, ts: Date.now() })
}
/**
* 是否展示新版三日报首页入口
* @param {string} merchantId 4S 店 shopMerchantId
* @returns {Promise<boolean>}
*/
export async function fetchDailyReportNewVersionMenuVisible(merchantId) {
const id = merchantId == null ? '' : String(merchantId).trim()
if (!id) {
return false
}
const cached = readCache(id)
if (cached !== null) {
return cached
}
const pending = pendingByMerchantId.get(id)
if (pending) {
return pending
}
const request = (async () => {
try {
const client = getApiClient()
const res = await client.dailyReportNewVersionIsNeed({ merchantId: id })
const visible = parseIsNeedResponse(res)
writeCache(id, visible)
return visible
} catch (error) {
writeCache(id, false)
return false
} finally {
pendingByMerchantId.delete(id)
}
})()
pendingByMerchantId.set(id, request)
return request
}