超时缓存类

2022-06-29  本文已影响0人  前端人

这个用来解决普通需要缓存的情况

const getHash = (str) => str;

class CacheObj {
  constructor(time) {
    this.cacheTime = time * 1000;
    this.mapObj = {};

    this.setCache = (key, cacheData) => {
      const keyTemp = getHash(key);
      this.mapObj[keyTemp] = {
        data: cacheData,
        startTime: new Date().getTime(),
      };
    };

    this.getCache = (key) => {
      const keyTmp = getHash(key);

      const data = this.mapObj[keyTmp];

      if (data && data.data) {
        if (new Date().getTime() - data.startTime <= this.cacheTime) {
          return data.data;
        }
      }

      return "";
    };
  }
}

export default CacheObj;
上一篇 下一篇

猜你喜欢

热点阅读