109 lines
2.1 KiB
JavaScript
109 lines
2.1 KiB
JavaScript
const CACHE_PREFIX = 'miniCache:'
|
|||
|
|
const memoryCache = {}
|
||
|
|
const inflightCache = {}
|
||
|
|
|
||
|
|
function now() {
|
||
|
|
return Date.now()
|
||
|
|
}
|
||
|
|
|
||
|
|
function buildKey(key) {
|
||
|
|
return `${CACHE_PREFIX}${key}`
|
||
|
|
}
|
||
|
|
|
||
|
|
function clearExpiredEntry(key, entry) {
|
||
|
|
if (!entry) {
|
||
|
|
return
|
||
|
|
}
|
||
|
|
if (entry.expireAt && entry.expireAt <= now()) {
|
||
|
|
delete memoryCache[key]
|
||
|
|
try {
|
||
|
|
wx.removeStorageSync(buildKey(key))
|
||
|
|
} catch (error) {}
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
function getCache(key, defaultValue) {
|
||
|
|
if (!key) {
|
||
|
|
return defaultValue
|
||
|
|
}
|
||
|
|
|
||
|
|
const localEntry = memoryCache[key]
|
||
|
|
if (localEntry && (!localEntry.expireAt || localEntry.expireAt > now())) {
|
||
|
|
return localEntry.value
|
||
|
|
}
|
||
|
|
clearExpiredEntry(key, localEntry)
|
||
|
|
|
||
|
|
try {
|
||
|
|
const storedEntry = wx.getStorageSync(buildKey(key))
|
||
|
|
if (storedEntry && (!storedEntry.expireAt || storedEntry.expireAt > now())) {
|
||
|
|
memoryCache[key] = storedEntry
|
||
|
|
return storedEntry.value
|
||
|
|
}
|
||
|
|
clearExpiredEntry(key, storedEntry)
|
||
|
|
} catch (error) {}
|
||
|
|
|
||
|
|
return defaultValue
|
||
|
|
}
|
||
|
|
|
||
|
|
function setCache(key, value, ttlMs) {
|
||
|
|
if (!key) {
|
||
|
|
return value
|
||
|
|
}
|
||
|
|
const expireAt = ttlMs && ttlMs > 0 ? now() + ttlMs : 0
|
||
|
|
const entry = {
|
||
|
|
value,
|
||
|
|
expireAt
|
||
|
|
}
|
||
|
|
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 removeByPrefix(prefix) {
|
||
|
|
Object.keys(memoryCache).forEach(key => {
|
||
|
|
if (key.startsWith(prefix)) {
|
||
|
|
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,
|
||
|
|
removeByPrefix,
|
||
|
|
remember
|
||
|
|
}
|