export default {
set(key: string, val: any, expire?: number | null) {
try {
let curTime = new Date().getTime();
expire = expire ? 1000 * expire : null;
wx.setStorageSync(
key,
JSON.stringify({
data: val,
saveTime: curTime,
expire,
})
);
} catch (e) {
console.error("缓存设置失败", e);
}
},
expired(key: string) {
try {
const data = wx.getStorageSync(key);
if (data) {
const dataObj = JSON.parse(data);
if (
dataObj.expire &&
new Date().getTime() - dataObj.saveTime > dataObj.expire
) {
return true;
} else {
return false;
}
}
return;
} catch (e) {
console.error(e);
return;
}
},
directGet(key: string) {
try {
const data = wx.getStorageSync(key);
if (data) {
const dataObj = JSON.parse(data);
return dataObj.data;
}
return null;
} catch (e) {
console.error("获取缓存失败", e);
}
},
get(key: string) {
try {
const data = wx.getStorageSync(key);
if (data) {
const dataObj = JSON.parse(data);
if (
dataObj.expire &&
new Date().getTime() - dataObj.saveTime > dataObj.expire
) {
this.remove(key);
return null;
} else {
return dataObj.data;
}
}
return null;
} catch (e) {
console.error("获取缓存失败", e);
}
},
remove(key: string) {
try {
wx.removeStorageSync(key);
} catch (e) {
console.error("缓存清除失败", e);
}
},
clear() {
try {
wx.clearStorage();
} catch (e) {
console.error("缓存清空失败", e);
}
},
};