Created
September 6, 2019 04:08
-
-
Save koo6357/a4a833a54040842709484e3d7af317e0 to your computer and use it in GitHub Desktop.
expire localStorage
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class ExpLocalStorage { | |
constructor() { | |
this.now = Math.floor(Date.now() / 1000); | |
this.initialize(); | |
} | |
initialize() { | |
if(!window || !window.localStorage) { | |
throw new Error("@@ localStorage is not available") | |
} | |
this.deleteExpiredStorage(); | |
} | |
keyName(key) { | |
return key.split('_')[1]; | |
} | |
keyExpTime(key) { | |
return Number(key.split('_').pop()); | |
} | |
set(key, value, expireTime) { | |
this.delete(key); | |
window.localStorage.setItem(`Exp_${key}_${this.now + (expireTime * 60)}`, JSON.stringify(value)); | |
} | |
get(key) { | |
const expKey = this.getAllExpStorage(); | |
const findKey = _.filter(expKey, _key => key === this.keyName(_key)); | |
return JSON.parse(window.localStorage.getItem(findKey)); | |
} | |
delete(key) { | |
const expKey = this.getAllExpStorage(); | |
_.filter(expKey, _key => { | |
if(this.keyName(_key) === key) { | |
window.localStorage.removeItem(_key); | |
} | |
}) | |
} | |
getAllExpStorage() { | |
return _.reduce(_.keys(window.localStorage), (list, _key) => { | |
if(_key.startsWith('Exp_')){ | |
list.push(_key); | |
return list; | |
} | |
return list; | |
}, []); | |
} | |
deleteExpiredStorage() { | |
_.forEach(_.keys(window.localStorage), (_key) => { | |
if(_key.startsWith('Exp_')){ | |
if(this.keyExpTime(_key) < this.now){ | |
window.localStorage.removeItem(_key); | |
} | |
} | |
}); | |
} | |
} | |
// Usage | |
const els = new ExpLocalStorage(); | |
els.set('state', {version: '1.0.0'}, 10); | |
els.get('state'); | |
els.delete('state'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment