cacheUtil.js 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. /**
  2. * 缓存数据优化
  3. * 使用方法 【
  4. * 一、设置缓存
  5. * cacheUtil.put('k', 'hello', 1000);
  6. * 二、读取缓存
  7. * cacheUtil.get('k')
  8. * 三、移除/清理
  9. * 移除: cache.remove('k');
  10. * 清理:cache.clear();
  11. * 】
  12. * @type {String}
  13. */
  14. var postfix = '_nazw_mini_cache'; // 缓存前缀
  15. /**
  16. * 设置缓存
  17. * @param {[type]} k [键名]
  18. * @param {[type]} v [键值]
  19. * @param {[type]} t [时间、单位秒]
  20. */
  21. function put(k, v, t) {
  22. wx.setStorageSync(k, v)
  23. var seconds = parseInt(t);
  24. if (seconds > 0) {
  25. var timestamp = Date.parse(new Date());
  26. timestamp = timestamp / 1000 + seconds;
  27. wx.setStorageSync(k + postfix, timestamp + "")
  28. } else {
  29. wx.removeStorageSync(k + postfix)
  30. }
  31. }
  32. /**
  33. * 获取缓存,不存在,过期为null
  34. * @param {[type]} k [键名]
  35. * @param {[type]} def [获取为空时默认]
  36. */
  37. function get(k, def) {
  38. var deadtime = parseInt(wx.getStorageSync(k + postfix))
  39. if (deadtime) {
  40. if (parseInt(deadtime) < Date.parse(new Date()) / 1000) {
  41. if (def) {
  42. return def;
  43. } else {
  44. remove(k)
  45. return null;
  46. }
  47. }
  48. }
  49. var res = wx.getStorageSync(k);
  50. if (res) {
  51. return res;
  52. } else {
  53. if (def == undefined) {
  54. def = null;
  55. }
  56. return def;
  57. }
  58. }
  59. function remove(k) {
  60. wx.removeStorageSync(k);
  61. wx.removeStorageSync(k + postfix);
  62. }
  63. /**
  64. * 清理所有缓存
  65. * @return {[type]} [description]
  66. */
  67. function clear() {
  68. wx.clearStorageSync();
  69. }
  70. module.exports = {
  71. cacheSet: put,
  72. cacheGet: get,
  73. cacheRemove: remove,
  74. cacheClear: clear,
  75. }