You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
48 lines
1.3 KiB
48 lines
1.3 KiB
/**
|
|
* 获取缓存
|
|
* @param String $key key
|
|
* @param String $def 若想要无缓存时,返回默认值则get('key','默认值')(支持字符串、json、数组、boolean等等)
|
|
* @return value;
|
|
*/
|
|
function get (key, def = '') {
|
|
const timeout = parseInt(wx.getStorageSync(`${key}__separator__`) || 0);
|
|
// 过期失效
|
|
if (timeout) {
|
|
if (Date.now() > timeout) {
|
|
this.remove(key);
|
|
return;
|
|
}
|
|
}
|
|
let value = wx.getStorageSync(key);
|
|
return value ? value : def;
|
|
}
|
|
|
|
/**
|
|
* 设置缓存
|
|
* @param String $key key
|
|
* @param String $value value(支持字符串、json、数组、boolean等等)
|
|
* @param Number $timeout 过期时间(单位:分钟)不设置时间即为永久保存
|
|
* @return value;
|
|
*/
|
|
function put (key, value, timeout = 0) {
|
|
let _timeout = parseInt(timeout);
|
|
wx.setStorageSync(key, value);
|
|
if (_timeout) {
|
|
wx.setStorageSync(`${key}__separator__`, Date.now() + 1000 * 60 * _timeout);
|
|
} else {
|
|
wx.removeStorageSync(`${key}__separator__`);
|
|
}
|
|
return value;
|
|
}
|
|
|
|
function remove (key) {
|
|
wx.removeStorageSync(key);
|
|
wx.removeStorageSync(`${key}__separator__`);
|
|
return undefined;
|
|
}
|
|
|
|
module.exports = {
|
|
remove: remove,
|
|
put: put,
|
|
get: get
|
|
}
|