前端控制 Axios 缓存

195 阅读1分钟

要实现什么效果:

对于请求比较频繁或不太常变化的接口,在http发送请求之前判断从缓存获取数据或重新发送请求。 前端可以通过参数控制是否缓存。

与HTTP缓存和使用框架 state 状态缓存的区别:

HTTP缓存:Http缓存指的是强制缓存强缓存和协商缓存。前者由浏览器本身机制控制,后者通过后端设置请求头(Cache-Control,Expires,ETag, Last-Modified) 控制,这些都不是前端可以主动控制的。

state缓存:state缓存值得是UI层面保存数据,比如通过VUE框架的vueX保存,这种方式的缺点是不同业务模块之间调用比较多时,容易使代码逻辑复杂化。

基于axios如何实现前端接口请求缓存:

function getCachedRequest(defaultCacheTime, requestIns = request) {
  const SourceCache = {};

  return (opts) => {
    const { cacheKey,cacheTime = defaultCacheTime, ...restOpts } = opts || {};

    const needCache = cacheTime >= 0;

    const finalCacheKey = cacheKey ? `${cacheKey}` : `cacheKey-${opts ? JSON.stringify(opts) : ''}`

    let reqPromise = needCache ? SourceCache[finalCacheKey] : null;

    if (!reqPromise) {

      reqPromise = requestIns({ ...restOpts });

      if (needCache) {
        reqPromise = reqPromise.then((result) => {
          if (cacheTime >= 0) {
            setTimeout(() => {
              SourceCache[finalCacheKey] = null;
              delete SourceCache[finalCacheKey];
            }, cacheTime);
          }

          return result;
        });
        SourceCache[finalCacheKey] = reqPromise;
      }
    }

    return reqPromise.then((resp) => {
      return cloneDeep(resp);
    });
  };
}

//request为原本的axios封装
const defaultCachedRequest = getCachedRequest(10000, request);

export const cachedRequest =  (...args) =>{
  return  defaultCachedRequest(...args).then((resp) => {
    return resp;
  });
}

现有的请求库

umi-requestgithub.com/umijs/umi-r…
基于 fetch 封装,自带缓存,错误检查等功能。

axios-cache-interceptor: axios-cache-interceptor.js.org/guide
基于axios封装,不同版本axios使用差异较大。支持Memory,Local Storag,Session Storage等多种方式保存数据,且支持自定义方式接入。

更多详情

arthur.place/implication…