家政小程序
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.

memory.js 2.5KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. import util from 'util';
  2. //内存数据
  3. const memoryData = {};
  4. const handler = {
  5. /***
  6. * 在全局对象的globalData里面获取数据
  7. * @param key[string]: 标识的key
  8. * @private
  9. */
  10. _getData(key) {
  11. //优先从内存获取数据,内存获取不到时再从磁盘获取
  12. if (memoryData[key]) return memoryData[key];
  13. let _localData = ''
  14. try {
  15. _localData = wx.getStorageSync && wx.getStorageSync(key)
  16. } catch (err) {
  17. console.log(err)
  18. }
  19. memoryData[key] = memoryData[key] || _localData || ''
  20. return memoryData[key];
  21. },
  22. /***
  23. * 在全局对象的globalData里面设置数据
  24. * @param key
  25. * @param val
  26. * @private
  27. */
  28. _setData(key, val, options) {
  29. if (memoryData[key]) {
  30. let old = memoryData[key];
  31. if (util.checkType(val) !== util.checkType(old)) {
  32. throw {
  33. message: '保存数据时请确认前后数据类型一致'
  34. };
  35. } else {
  36. if (Array.isArray(old)) {
  37. memoryData[key] = [];
  38. val.forEach(item => {
  39. memoryData[key].push(item);
  40. });
  41. } else if (typeof old === 'object') {
  42. memoryData[key] = util.assign({}, val);
  43. } else {
  44. memoryData[key] = val;
  45. }
  46. }
  47. } else {
  48. memoryData[key] = val;
  49. }
  50. //如果数据指定在磁盘上也保存,则向磁盘也写数据
  51. if (options && options.localSave) {
  52. try {
  53. wx.setStorageSync && wx.setStorageSync(key, memoryData[key])
  54. // memoryData[key].local = true
  55. } catch (err) {
  56. console.log(err)
  57. }
  58. }
  59. },
  60. _getDataWithExpire(key) {
  61. const now = Math.round(+new Date() / 1000)
  62. const c = handler._getData(key)
  63. if (!c || now > c._expiredAt) {
  64. return null
  65. }
  66. return c.val
  67. },
  68. _setDataWithExpire(key, val, options) {
  69. const ttl = options.ttl || 600
  70. const now = Math.round(+new Date() / 1000)
  71. const _expiredAt = now + ttl
  72. handler._setData(key, {
  73. _expiredAt,
  74. val
  75. }, options)
  76. },
  77. };
  78. export default {
  79. getData: handler._getData,
  80. setData: handler._setData,
  81. getDataWithExpire: handler._getDataWithExpire,
  82. setDataWithExpire: handler._setDataWithExpire,
  83. };