https://www.npmjs.com/package/expired-storage?activeTab=readme
This library extends localStroage. When setting the item, another key will be set to store the expiration time. When fetching data, determine whether it is expired and remove the element.
Usage
expiredStorage = new ExpiredStorage();
// 60秒后过期
expiredStorage.setItem("test", "foobar", 60);
// 永不过期
expiredStorage.setItem("no_expire", "this will live forever");
// 获取数据,如果过期会返回null
var item = expiredStorage.getItem("test");
// 获取剩余时间
var timeLeft = expiredStorage.getTimeLeft("test");
// 检测key是否过期
var isExpired = expiredStorage.isExpired("test");
// 获取所有的key(如果includeExpired是true, 连过期没来的删除的key也一并返回)
var keys = expiredStorage.keys(includeExpired);
// 返回这个key的详情
var data = expiredStorage.peek("test");
source code interpretation
Constructor, this is some boundary judgment, nothing
function ExpiredStorage(storage) {
...
this._storage = storage;
}
The focus is setItem
and getItem
ExpiredStorage.prototype = {
// 基础stroage类,在构造函数中赋值
_storage: null,
// 时间戳key的前缀
_expiration_key_prefix: "__expired_storage_ts__",
// 获取当前时间 单位秒
getTimestamp: function() {
return Math.floor(((new Date).getTime()) / 1000);
},
setItem: function(key, value, expiration) {
// set item
var ret = this._storage.setItem(key, value);
// 存储这个key对应的过期时间 (仅仅在expiration有值的时候)
if (expiration) {
this.updateExpiration(key, expiration);
}
return ret;
},
// 更新key的过期时间,新的key位时间戳前缀加旧的key
updateExpiration: function(key, expiration) {
return this._storage.setItem(this._expiration_key_prefix + key, this.getTimestamp() + expiration);
},
getItem: function(key) {
// 判断是否过期,过期了就删除这一项,返回null
if (this.isExpired(key)) {
this.removeItem(key);
return null;
}
// 没过期就正常返回
return this._storage.getItem(key);
},
// 判断是否过期
isExpired: function(key) {
var timeLeft = this.getTimeLeft(key);
return timeLeft !== null && timeLeft <= 0;
},
// 获取剩余时间
getTimeLeft: function(key) {
// 通过时间戳key拿到过期时间
var expireTime = parseInt(this._storage.getItem(this._expiration_key_prefix + key));
// 取到值就返回剩余时间
if (expireTime && !isNaN(expireTime)) {
return expireTime - this.getTimestamp();
}
// 没取到值就返回null
return null;
},
// 同时删除key和时间戳key
removeItem: function(key) {
var ret = this._storage.removeItem(key);
this._storage.removeItem(this._expiration_key_prefix + key);
return ret;
},
}
It is very simple to achieve a more troublesome requirement. This warehouse has not been updated for four years, and it still maintains a download volume of about 1k per week. Admire! !
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。