功能:收口小程序前后台安全与防重复提交

This commit is contained in:
xiaowang
2026-04-20 16:02:57 +08:00
parent eb1c209d79
commit a3df262fae
237 changed files with 14068 additions and 728 deletions
+83
View File
@@ -0,0 +1,83 @@
const CACHE_PREFIX = 'adminMiniCache:'
const memoryCache = {}
const inflightCache = {}
function buildKey(key) {
return `${CACHE_PREFIX}${key}`
}
function now() {
return Date.now()
}
function getCache(key, defaultValue) {
if (!key) {
return defaultValue
}
const memoryEntry = memoryCache[key]
if (memoryEntry && (!memoryEntry.expireAt || memoryEntry.expireAt > now())) {
return memoryEntry.value
}
delete memoryCache[key]
try {
const storedEntry = wx.getStorageSync(buildKey(key))
if (storedEntry && (!storedEntry.expireAt || storedEntry.expireAt > now())) {
memoryCache[key] = storedEntry
return storedEntry.value
}
wx.removeStorageSync(buildKey(key))
} catch (error) {}
return defaultValue
}
function setCache(key, value, ttlMs) {
if (!key) {
return value
}
const entry = {
value,
expireAt: ttlMs && ttlMs > 0 ? now() + ttlMs : 0
}
memoryCache[key] = entry
try {
wx.setStorageSync(buildKey(key), entry)
} catch (error) {}
return value
}
function removeCache(key) {
if (!key) {
return
}
delete memoryCache[key]
try {
wx.removeStorageSync(buildKey(key))
} catch (error) {}
}
function remember(key, ttlMs, loader) {
const cached = getCache(key, undefined)
if (cached !== undefined) {
return Promise.resolve(cached)
}
if (inflightCache[key]) {
return inflightCache[key]
}
inflightCache[key] = Promise.resolve()
.then(() => loader())
.then(value => setCache(key, value, ttlMs))
.finally(() => {
delete inflightCache[key]
})
return inflightCache[key]
}
module.exports = {
getCache,
setCache,
removeCache,
remember
}