ts_aimz/utils/cache.js

53 lines
1.2 KiB
JavaScript
Raw Permalink Normal View History

2025-03-21 09:02:29 +08:00
// 缓存工具类
const CACHE_PREFIX = 'ts_mz_';
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;