如何让localStorage支持过期时间设置?

文章目录

  • 前言
  • 1. 初级解法
  • 2. 中级解法
  • 3.高级解法


前言

问题描述:在实际的应用场景中, 我们往往需要让localStorage 设置的某个 「key」 能在指定时间内自动失效, 所以基于这种场景, 我们如何去解决呢?


1. 初级解法

localStorage.setItem('dooring', '1.0.0')
// 设置一小时的有效期
const expire = 1000 * 60 * 60;
setTimeout(() => {
  localStorage.setItem('dooring', '')
}, expire)

当然这种方案能解决一时的问题, 但是如果要设置任意键的有效期, 使用这种方案就需要编写多个定时器, 「维护成本极高, 且不利于工程化复用」

2. 中级解法

  1. 用「localStorage」存一份{key(键): expire(过期时间)}的映射表
  2. 重写「localStorage API」, 对方法进行二次封装

代码如下(示例):

const store = {
  // 存储过期时间映射
  setExpireMap: (key, expire) => {
    const expireMap = localStorage.getItem('EXPIRE_MAP') || "{}"
    localStorage.setItem(
      'EXPIRE_MAP', 
      JSON.stringify({
      ...JSON.parse(expireMap),
      key: expire
    }))
  },
  setItem: (key, value, expire) => {
    store.setExpireMap(key, expire)
    localStorage.setItem(key, value)
  },
  getItem: (key) => {
    // 在取值之前先判断是否过期
    const expireMap = JSON.parse(
      localStorage.getItem('EXPIRE_MAP') || "{}"
    )
    if(expireMap[key] && expireMap[key] < Date.now()) {
      return localStorage.getItem(key)
    }else {
      localStorage.removeItem(key)
      return null
    }
  }
}

眨眼一看这个方案确实解决了复用性的问题, 并且不同团队都可以使用这个方案, 但仍然有一些缺点:
● 对 store 操作时需要维护2份数据, 并且占用缓存空间
● 如果 EXPIRE_MAP 误删除将会导致所有过期时间失效
● 对操作过程缺少更灵活的控制(比如操作状态, 操作回调等)

3.高级解法

为了减少维护成本和空间占用, 并支持一定的灵活控制和容错能力, 我们又应该怎么做呢?
这里笔者想到了两种类似的方案:

  1. 将过期时间存到 key 中, 如 dooring|6000, 每次取值时通过分隔符“|”来将 key 和 expire 取出, 进行判断
  2. 将过期时间存到 value 中, 如 1.0.0|6000, 剩下的同1
    为了更具有封装性和可靠性, 我们还可以配置不同状态下的回调, 简单实现如下:
const store = {
  preId: 'xi-',
  timeSign: '|-door-|',
  status: {
    SUCCESS: 0,
    FAILURE: 1,
    OVERFLOW: 2,
    TIMEOUT: 3,
  },
  storage: localStorage || window.localStorage,
  getKey: function (key: string) {
    return this.preId + key;
  },
  set: function (
    key: string,
    value: string | number,
    time?: Date & number,
    cb?: (status: number, key: string, value: string | number) => void,
  ) {
    let _status = this.status.SUCCESS,
      _key = this.getKey(key),
      _time;
    // 设置失效时间,未设置时间默认为一个月
    try {
      _time = time
        ? new Date(time).getTime() || time.getTime()
        : new Date().getTime() + 1000 * 60 * 60 * 24 * 31;
    } catch (e) {
      _time = new Date().getTime() + 1000 * 60 * 60 * 24 * 31;
    }
    try {
      this.storage.setItem(_key, _time + this.timeSign + value);
    } catch (e) {
      _status = this.status.OVERFLOW;
    }
    cb && cb.call(this, _status, _key, value);
  },
  get: function (
    key: string,
    cb?: (status: number, value: string | number | null) => void,
  ) {
    let status = this.status.SUCCESS,
      _key = this.getKey(key),
      value = null,
      timeSignLen = this.timeSign.length,
      that = this,
      index,
      time,
      result;
    try {
      value = that.storage.getItem(_key);
    } catch (e) {
      result = {
        status: that.status.FAILURE,
        value: null,
      };
      cb && cb.call(this, result.status, result.value);
      return result;
    }
    if (value) {
      index = value.indexOf(that.timeSign);
      time = +value.slice(0, index);
      if (time > new Date().getTime() || time == 0) {
        value = value.slice(index + timeSignLen);
      } else {
        (value = null), (status = that.status.TIMEOUT);
        that.remove(_key);
      }
    } else {
      status = that.status.FAILURE;
    }
    result = {
      status: status,
      value: value,
    };
    cb && cb.call(this, result.status, result.value);
    return result;
  }
};

export default store;

这样, 我们就实现了每个 key 都有独立的过期时间, 并且对不同的操作结果可以轻松的进行状态管控啦~ 参考文档:面试官: 如何让localStorage支持过期时间设置?

你可能感兴趣的:(菜鸟成长,javascript)