- 1、原创力文档(book118)网站文档一经付费(服务费),不意味着购买了该文档的版权,仅供个人/单位学习、研究之用,不得用于商业用途,未经授权,严禁复制、发行、汇编、翻译或者网络传播等,侵权必究。。
- 2、本站所有内容均由合作方或网友上传,本站不对文档的完整性、权威性及其观点立场正确性做任何保证或承诺!文档内容仅供研究参考,付费前请自行鉴别。如您付费,意味着您自己接受本站规则且自行承担风险,本站不退款、不进行额外附加服务;查看《如何避免下载的几个坑》。如果您已付费下载过本站文档,您可以点击 这里二次下载。
- 3、如文档侵犯商业秘密、侵犯著作权、侵犯人身权等,请点击“版权申诉”(推荐),也可以打举报电话:400-050-0827(电话支持时间:9:00-18:30)。
第
JavaScript手写一个前端存储工具库
目录使用storage-tools缓存数据storage-tools项目演进StorageHelper支持localStorage存储StorageHelper添加超时机制StorageHelper添加其他存储适配StorageHelper添加异步获取列表辅助类ListStorageHelper在项目开发的过程中,为了减少提高性能,减少请求,开发者往往需要将一些不易改变的数据放入本地缓存中。如把用户使用的模板数据放入localStorage或者IndexedDB。代码往往如下书写。
//这里将数据放入内存中
lettemplatesCache=null;
//用户id,用于多账号系统
constuserId:string=1;
constgetTemplates=({
refresh=false
}={
refresh:false
})={
//不需要立即刷新,走存储
if(!refresh){
//内存中有数据,直接使用内存中数据
if(templatesCache){
returnPromise.resolve(templatesCache)
constkey=`templates.${userId}`
//从localStorage中获取数据
consttemplateJSONStr=localStroage.getItem(key)
if(templateJSONStr){
try{
templatesCache=JSON.parse(templateJSONStr);
returnPromise.resolve(templatesCache)
}catch(){
//解析失败,清除storage中数据
localStroage.removeItem(key)
//进行服务端掉用获取数据
returnapi.get(xxx).then(res={
templatesCache=cloneDeep(res)
//存入本地缓存
localStroage.setItem(key,JSON.stringify(templatesCache))
returnres
};
可以看到,代码非常冗余,同时这里的代码还没有处理数据版本、过期时间以及数据写入等功能。如果再把这些功能点加入,代码将会更加复杂,不易维护。
于是个人写了一个小工具storage-tools来处理这个问题。
使用storage-tools缓存数据
该库默认使用localStorage作为数据源,开发者从库中获取StorageHelper工具类。
import{StorageHelper}fromstorage-tools;
//当前用户id
constuserId=1;
//构建模版store
//构建时候就会获取localStorage中的数据放入内存
consttemplatesStore=newStorageHelper({
//多账号用户使用key
storageKey:`templates.${userId}`,
//当前数据版本号,可以从后端获取并传入
version:1,
//超时时间,单位为秒
timeout:60*60*24,
//从内存中获取数据
consttemplates=templatesStore.getData();
//没有数据,表明数据过期或者没有存储过
if(templates===null){
api.get(xxx).then((val)={
//存储数据到内存中去,之后的getData都可以获取到数据
store.setData(val);
//闲暇时间将当前内存数据存储到localStorage中
requestIdleCallback(()={
//期间内可以多次掉用setData
mit();
}
StorageHelper工具类支持了其他缓存源,代码如下:
import{IndexedDBAdaptor,StorageAdaptor,StorageHelper}fromstorage-tools;
//当前用户id
constu
文档评论(0)