当前位置:网站首页>How to make localstorage support expiration time setting?
How to make localstorage support expiration time setting?
2022-07-21 16:00:00 【Xianling Pavilion】
Talk about localStorage Presumably, friends who are familiar with the front end will not be unfamiliar , We can use the getItem, setItem, removeItem, clear These are a few API The data stored locally in the browser can be easily **「 read , Write , Delete 」 operation , But compared to cookie, localStorage The only drawback is 「 You cannot set the expiration time of each key 」**.
localStorage Property allows us to access a Document Source (origin) The object of Storage; The stored data will be saved in the browser session . localStorage similar sessionStorage, But the difference is : Stored in localStorage The data can be kept for a long time ; And when the page session ends —— in other words , When the page is closed , Stored in sessionStorage The data will be cleared .
We should also pay attention to ,localStorage Key value pairs in are always stored as strings .
Problem description
In a real application scenario , We often need to let localStorage Set one of 「key」 It can automatically expire within a specified time , So based on this scenario , How can we solve it ?
1. Primary solution
For friends who are just familiar with the front end , May give the answer immediately :
localStorage.setItem('dooring', '1.0.0')
// Set the validity period of one hour
const expire = 1000 * 60 * 60;
setTimeout(() => {
localStorage.setItem('dooring', '')
}, expire)
Copy code
Of course, this solution can solve the temporary problem , But if you want to set the validity of any key , Using this scheme requires writing multiple timers , 「 Maintenance costs are very high , And it is not conducive to engineering reuse 」.
2. Intermediate solution
Front end engineer after having some work experience , We often think about engineering and reusability , And have a certain understanding of the data structure , So there may be the next solution :
1. use **「localStorage」 Keep a copy of {key( key ): expire( Expiration time )} Mapping table
2. rewrite 「localStorage API」**, Secondary encapsulation of the method
Similar code is as follows :
const store = {
// Store expiration time mapping
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) => {
// Judge whether it is expired before taking value
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
}
}
// ...
}
Copy code
In the blink of an eye, this solution does solve the problem of reusability , And different teams can use this scheme , But there are still some shortcomings :
- Yes store Maintenance is required during operation 2 Copy of the data , And take up cache space
- If EXPIRE_MAP Deleting by mistake will invalidate all expiration times
- Lack of more flexible control over the operation process ( Such as operation status , Operation callback, etc )
3. Advanced solution
In order to reduce maintenance costs and space occupation , And support certain flexible control and fault tolerance , What should we do ?
Here the author comes up with two similar schemes :
1. Save the expiration time to key in , Such as dooring|6000, Each time you take a value, use the separator “|” to key and expire Take out , Judge
2. Save the expiration time to value in , Such as 1.0.0|6000, The rest are the same 1
For more encapsulation and reliability , We can also configure callbacks in different states , The simple implementation is as follows :
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;
// Set the expiration time , If the time is not set, it defaults to one month
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;
Copy code
such , We have achieved every key There is an independent expiration time , And you can easily control the state of different operation results ~
4. Ashes solution
Of course , Ashes level solution is used directly xijs This javascript Tool library , Because I have encapsulated the above complete implementation scheme into the Library , We only need to use the following scheme , You can easily use powerful with expiration time 「localStorage」 Methods! :
// Install first yarn add xijs
import {
store } from 'xijs';
// Set... With expiration time key
store.set('name', 'dooring', Date.now() + 1000);
console.log(store.get('name'));
setTimeout(() => {
console.log(store.get('name'));
}, 1000);
// Callback after successful setting
store.set('dooring', 'xuxiaoxi', Date.now() + 1000, (status, key, value) => {
console.log('success');
});
Copy code
meanwhile xijs Still expanding more useful tool functions , Make business development more efficient . At present, the following tool functions have been integrated :
「store」 be based on localStorage The cache library encapsulated in the upper layer supports expiration time setting , Support operation callback
「uuid」 Generating uniqueness id, Support to set the length
「randomStr」 Generate a specified number of random strings
「formatDate」 Out of the box time formatting tool
「debounce」 Anti shake function
「throttle」 Throttling function
「url2obj」 take url String to object
「obj2url」 Convert the object to encoded url character string
「isPC」 Determine if the device is PC type
The source code attachment has been packaged and uploaded to Baidu cloud , You can download it yourself ~
link : https://pan.baidu.com/s/14G-bpVthImHD4eosZUNSFA?pwd=yu27
Extraction code : yu27
Baidu cloud link is unstable , It may fail at any time , Let's keep it tight .
If Baidu cloud link fails , Please leave me a message , When I see it, I will update it in time ~
Open source address
Code cloud address :
http://github.crmeb.net/u/defu
Github Address :
http://github.crmeb.net/u/defu
link :https://juejin.cn/post/7040671388025225229
边栏推荐
- net core 3.1使用identityServer登录时signin-oidc报Correlation failed的解决方法
- 小程序毕设作品之微信疫苗预约小程序毕业设计(2)小程序功能
- Wechat vaccine appointment applet graduation design of applet completion work (2) applet function
- 修改标注样式文字填充颜色
- 墨家巡逻兵 源码
- 解决突然跳出命令行(闪烁)
- CAD2014 X64 调试arx
- ROS从入门到精通(十) TF坐标变换原理,为什么需要TF变换?
- Wechat vaccine appointment applet graduation project of applet completion work (4) opening report
- 【Example】在输入框内输入文本,输出打字机效果
猜你喜欢
小程序毕设作品之微信疫苗预约小程序毕业设计(7)中期检查报告
[error]runtimeerror: expected scalar type double but found float (torch)
c || 文件操作
TransUNet: Transformers Make Strong Encoders for Medical Image Segmentation
Wechat vaccine appointment applet graduation project of applet completion work (6) opening defense ppt
未来旅游新方式,VR云游足不出户拥抱诗和远方
How to modify the default path of CONDA virtual environment
这款国产API神器工具也太强了吧...让我放弃了postman
目前最火的测试框架,pytest封神级讲解
Can physical layer introduction
随机推荐
Survey and Systematization of 3D Object Detection Models and Methods(3D目标检测模型与方法综述)论文笔记
小程序毕设作品之微信疫苗预约小程序毕业设计(6)开题答辩PPT
c || 数组与指针
Shape and boundary-aware multi-branch model for semi-supervised medical image segmentation
Dynamic characteristics and interaction in virtual environment
【JS】标签页切换
Imitate the widget control of VTK, and make the control that draws a rectangle
【JS】事件传播
【STC15控制WS2812 RGB彩灯级联】
[error]runtimeerror: expected scalar type double but found float (torch)
Programming - common sense CS
Oracle一条语句实现更新or新增
[Yugong series] go teaching course in July 2022 014 arithmetic operators of operators
C | file operation
解决突然跳出命令行(闪烁)
CAD2014 X64 调试arx
BluePrism工具菜单栏用户权限功能描述-RPA第二章
小程序毕设作品之微信疫苗预约小程序毕业设计(2)小程序功能
算法总结] 20 道题搞定 BAT 面试——二叉树
Can physical layer introduction