54 lines
1.1 KiB
JavaScript
54 lines
1.1 KiB
JavaScript
// 缓存工具类
|
|
const CACHE_PREFIX = 'daqi_';
|
|
const DEFAULT_CACHE_TIME = 5 * 60 * 1000; // 默认缓存5分钟
|
|
|
|
class Cache {
|
|
/**
|
|
* 设置缓存
|
|
* @param {string} key 缓存键
|
|
* @param {any} value 缓存值
|
|
* @param {number} expire 过期时间(毫秒)
|
|
*/
|
|
static set(key, value, expire = DEFAULT_CACHE_TIME) {
|
|
const data = {
|
|
value,
|
|
expire: expire ? new Date().getTime() + expire : null
|
|
};
|
|
wx.setStorageSync(CACHE_PREFIX + key, JSON.stringify(data));
|
|
}
|
|
|
|
/**
|
|
* 获取缓存
|
|
* @param {string} key 缓存键
|
|
* @returns {any} 缓存值
|
|
*/
|
|
static get(key) {
|
|
const data = wx.getStorageSync(CACHE_PREFIX + key);
|
|
if (!data) return null;
|
|
|
|
const cache = JSON.parse(data);
|
|
if (cache.expire && cache.expire < new Date().getTime()) {
|
|
wx.removeStorageSync(CACHE_PREFIX + key);
|
|
return null;
|
|
}
|
|
return cache.value;
|
|
}
|
|
|
|
/**
|
|
* 删除缓存
|
|
* @param {string} key 缓存键
|
|
*/
|
|
static remove(key) {
|
|
wx.removeStorageSync(CACHE_PREFIX + key);
|
|
}
|
|
|
|
/**
|
|
* 清空所有缓存
|
|
*/
|
|
static clear() {
|
|
wx.clearStorageSync();
|
|
}
|
|
}
|
|
|
|
module.exports = Cache;
|