12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879 |
- /**
- * 缓存数据优化
- * 使用方法 【
- * 一、设置缓存
- * cacheUtil.put('k', 'hello', 1000);
- * 二、读取缓存
- * cacheUtil.get('k')
- * 三、移除/清理
- * 移除: cache.remove('k');
- * 清理:cache.clear();
- * 】
- * @type {String}
- */
- var postfix = '_nazw_mini_cache'; // 缓存前缀
- /**
- * 设置缓存
- * @param {[type]} k [键名]
- * @param {[type]} v [键值]
- * @param {[type]} t [时间、单位秒]
- */
- function put(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 + postfix, timestamp + "")
- } else {
- wx.removeStorageSync(k + postfix)
- }
- }
- /**
- * 获取缓存,不存在,过期为null
- * @param {[type]} k [键名]
- * @param {[type]} def [获取为空时默认]
- */
- function get(k, def) {
- var deadtime = parseInt(wx.getStorageSync(k + postfix))
- if (deadtime) {
- if (parseInt(deadtime) < Date.parse(new Date()) / 1000) {
- if (def) {
- return def;
- } else {
- remove(k)
- return null;
- }
- }
- }
- var res = wx.getStorageSync(k);
- if (res) {
- return res;
- } else {
- if (def == undefined) {
- def = null;
- }
- return def;
- }
- }
- function remove(k) {
- wx.removeStorageSync(k);
- wx.removeStorageSync(k + postfix);
- }
- /**
- * 清理所有缓存
- * @return {[type]} [description]
- */
- function clear() {
- wx.clearStorageSync();
- }
- module.exports = {
- cacheSet: put,
- cacheGet: get,
- cacheRemove: remove,
- cacheClear: clear,
- }
|