基于uniapp缓存api封装的可设置缓存时间的函数

134 阅读1分钟

前言

最近在做小程序时, 有一个需求需要去获取用户的经纬度, 然而考虑到用户自身位置可能会变化,并且没有类似于H5的SessionStorage(当然这种也可以考虑用全局变量来缓存[不优雅,且考虑到后续可能会有其他也需要设置缓存时间的需求]),因此有了这次简单的api封装路程

封装和分析

方案分析

关于经纬度的获取的两种方案

  1. 每次获取的时候都去调用uni.getLocation() api , 但是很显然,每次都去调用api,多多少少会进行一些操作,影响性能;并且无用且重复的代码量也会变多
  2. 给经纬度的缓存设置缓存时间,时间结束时,重新获取;时间没有结束,延用缓存值

代码封装

 /**
     * @Description: 设置缓存
     * @param {key}
     * @param {value}
     * @param {cacheTime} 缓存时间
     * @param {options} 预留字段
     * @return 
     */
    _uni.setStorageSync = function (key, value, cacheTime, options = {}) {
      // 1. 缓存值为空
      if (value == undefined) {
        throw new Error('不允许缓存空值');
      }
      // 2. 不存在缓存时间,直接存值
      if (cacheTime == undefined) {
        uni.setStorageSync(key, value);
        return;
      }
      // 3. 存在缓存时间,存值
      uni.setStorageSync(key, {
        cacheContent: value,
        cacheTime,
        createTime: Date.now(),
      });
    };
    
     // 获取缓存值
    _uni.getStorageSync = function (key) {
      const value = uni.getStorageSync(key);

      // 对象
      if (typeof value == 'object') {
        const { createTime, cacheTime, cacheContent } = value;
        // 存在缓存时间
        if (
          createTime &&
          cacheTime &&
          typeof createTime == 'number' &&
          typeof cacheTime == 'number'
        ) {
          // 过期清空
          const now = Date.now();
          if (Math.floor(now - createTime) >= cacheTime) {
            return null;
          }
          return cacheContent;
        }
      }
      // 其他(兼容以前的写法)
      return value;
    };