123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107 |
- const cacheManager = (function() {
- // 默认存储的前缀,可以根据需要修改
- const STORAGE_PREFIX = 'App_cache_';
- // 设置缓存
- function set(key, value) {
- const fullKey = STORAGE_PREFIX + key;
- if (typeof value === 'object' && value !== null) {
- // 如果是对象,则将其转换为字符串存储
- uni.setStorageSync(fullKey, JSON.stringify(value));
- } else {
- uni.setStorageSync(fullKey, value);
- }
- }
- // 获取缓存
- function get(key) {
- const fullKey = STORAGE_PREFIX + key;
- const value = uni.getStorageSync(fullKey);
- try {
- // 尝试将字符串解析为对象
- return JSON.parse(value);
- } catch (e) {
- // 如果解析失败,则直接返回值
- return value;
- }
- }
- // 删除缓存
- function remove(key) {
- const fullKey = STORAGE_PREFIX + key;
- uni.removeStorageSync(fullKey);
- }
- // 增量修改对象中的参数或添加新参数 删除参数
- //例子: cacheManager.updateObject('user', { www: undefined }); //删除
- function updateObject(key, updates) {
- let obj = get(key) || {};
- // 合并更新到对象中
- //Object.assign(obj, updates);
- for (let [keyToUpdate, value] of Object.entries(updates)) {
- if (value === null || value === undefined) {
- // 如果值为 null 或 undefined,则删除属性
- delete obj[keyToUpdate];
- } else {
- // 否则,更新或添加属性
- obj[keyToUpdate] = value;
- }
- }
- // 重新设置缓存
- set(key, obj);
- }
- // 清除所有以特定前缀开头的缓存
- function clearAll() {
- const keys = uni.getStorageInfoSync().keys;
- keys.forEach(key => {
- if (key.startsWith(STORAGE_PREFIX)) {
- uni.removeStorageSync(key);
- }
- });
- }
- // 增量修改对象中的数组,支持添加、更新和删除元素
- function updateArrayInObject(key, arrayPath, updateFn) {
- let obj = get(key) || {};
- // 根据arrayPath找到需要修改的数组
- const targetArray = findArrayInObject(obj, arrayPath);
- if (Array.isArray(targetArray)) {
- // 应用更新函数到目标数组上
- updateFn(targetArray);
- // 重新设置缓存
- set(key, obj);
- } else {
- console.error(`Path ${arrayPath} does not point to an array in the object.`);
- }
- }
- // 例子
- // cacheManager.updateArrayInObject('user', 'hobbies', (hobbies) => {
- // hobbies.push('reading');
- // hobbies = 'coding';
- // hobbies.pop();
- // });
- // 在对象中根据路径找到数组
- function findArrayInObject(obj, path) {
- return path.split('.').reduce((acc, curr) => {
- if (acc && acc[curr] !== undefined) {
- return acc[curr];
- } else {
- return undefined;
- }
- }, obj);
- }
- return {
- set,
- get,
- remove,
- updateObject,
- findArrayInObject,
- clearAll
- };
- })();
- export default cacheManager;
|