问题描述:在实际的应用场景中, 我们往往需要让localStorage
设置的某个 「key」
能在指定时间内自动失效, 所以基于这种场景, 我们如何去解决呢?
localStorage.setItem('dooring', '1.0.0')
// 设置一小时的有效期
const expire = 1000 * 60 * 60;
setTimeout(() => {
localStorage.setItem('dooring', '')
}, expire)
当然这种方案能解决一时的问题, 但是如果要设置任意键的有效期, 使用这种方案就需要编写多个定时器, 「维护成本极高, 且不利于工程化复用」。
代码如下(示例):
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 误删除将会导致所有过期时间失效
● 对操作过程缺少更灵活的控制(比如操作状态, 操作回调等)
为了减少维护成本和空间占用, 并支持一定的灵活控制和容错能力, 我们又应该怎么做呢?
这里笔者想到了两种类似的方案:
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支持过期时间设置?