超時緩存類

這個用來解決普通需要緩存的情況

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;
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章