cacheManager.js 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. const cacheManager = (function() {
  2. // 默认存储的前缀,可以根据需要修改
  3. const STORAGE_PREFIX = 'App_cache_';
  4. // 设置缓存
  5. function set(key, value) {
  6. const fullKey = STORAGE_PREFIX + key;
  7. if (typeof value === 'object' && value !== null) {
  8. // 如果是对象,则将其转换为字符串存储
  9. uni.setStorageSync(fullKey, JSON.stringify(value));
  10. } else {
  11. uni.setStorageSync(fullKey, value);
  12. }
  13. }
  14. // 获取缓存
  15. function get(key) {
  16. const fullKey = STORAGE_PREFIX + key;
  17. const value = uni.getStorageSync(fullKey);
  18. try {
  19. // 尝试将字符串解析为对象
  20. return JSON.parse(value);
  21. } catch (e) {
  22. // 如果解析失败,则直接返回值
  23. return value;
  24. }
  25. }
  26. // 删除缓存
  27. function remove(key) {
  28. const fullKey = STORAGE_PREFIX + key;
  29. uni.removeStorageSync(fullKey);
  30. }
  31. // 增量修改对象中的参数或添加新参数 删除参数
  32. //例子: cacheManager.updateObject('user', { www: undefined }); //删除
  33. function updateObject(key, updates) {
  34. let obj = get(key) || {};
  35. // 合并更新到对象中
  36. //Object.assign(obj, updates);
  37. for (let [keyToUpdate, value] of Object.entries(updates)) {
  38. if (value === null || value === undefined) {
  39. // 如果值为 null 或 undefined,则删除属性
  40. delete obj[keyToUpdate];
  41. } else {
  42. // 否则,更新或添加属性
  43. obj[keyToUpdate] = value;
  44. }
  45. }
  46. // 重新设置缓存
  47. set(key, obj);
  48. }
  49. // 清除所有以特定前缀开头的缓存
  50. function clearAll() {
  51. const keys = uni.getStorageInfoSync().keys;
  52. keys.forEach(key => {
  53. if (key.startsWith(STORAGE_PREFIX)) {
  54. uni.removeStorageSync(key);
  55. }
  56. });
  57. }
  58. // 增量修改对象中的数组,支持添加、更新和删除元素
  59. function updateArrayInObject(key, arrayPath, updateFn) {
  60. let obj = get(key) || {};
  61. // 根据arrayPath找到需要修改的数组
  62. const targetArray = findArrayInObject(obj, arrayPath);
  63. if (Array.isArray(targetArray)) {
  64. // 应用更新函数到目标数组上
  65. updateFn(targetArray);
  66. // 重新设置缓存
  67. set(key, obj);
  68. } else {
  69. console.error(`Path ${arrayPath} does not point to an array in the object.`);
  70. }
  71. }
  72. // 例子
  73. // cacheManager.updateArrayInObject('user', 'hobbies', (hobbies) => {
  74. // hobbies.push('reading');
  75. // hobbies = 'coding';
  76. // hobbies.pop();
  77. // });
  78. // 在对象中根据路径找到数组
  79. function findArrayInObject(obj, path) {
  80. return path.split('.').reduce((acc, curr) => {
  81. if (acc && acc[curr] !== undefined) {
  82. return acc[curr];
  83. } else {
  84. return undefined;
  85. }
  86. }, obj);
  87. }
  88. return {
  89. set,
  90. get,
  91. remove,
  92. updateObject,
  93. findArrayInObject,
  94. clearAll
  95. };
  96. })();
  97. export default cacheManager;