cache.js 2.0 KB

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