带过期时间的小程序StorageSync缓存实现
var dtime = '_deadtime';
//设置缓存
function cachePut(k, v, t) {
wx.setStorageSync(k,v)
var seconds = parseInt(t);
if (seconds > 0) {
var timestamp = Date.parse(new Date());
timestamp = timestamp / 1000 + seconds;
wx.setStorageSync(k + dtime, timestamp + "")
} else {
wx.removeStorageSync(k + dtime)
}
}
//获取缓存
function cacheGet(k, def) {
var deadtime = parseInt(wx.getStorageSync(k + dtime))
if (deadtime) {
if (parseInt(deadtime) < Date.parse(new Date()) / 1000) {
if (def) { return def; } else { return; }
}
}
var res = wx.getStorageSync(k);
if (res) {
return res;
} else {
return def;
}
}
//删除指定缓冲
function cacheRem(k) {
wx.removeStorageSync(k);
wx.removeStorageSync(k + dtime);
}
//清空所有缓存
function cacheClear() {
wx.clearStorageSync();
}
module.exports = {
cachePut: cachePut,
cacheGet: cacheGet,
cacheRem: cacheRem,
cacheClear: cacheClear,
}