84 lines
1.6 KiB
JavaScript
84 lines
1.6 KiB
JavaScript
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
|
||
|
|
}
|