Created
February 21, 2020 10:13
-
-
Save meded90/2468d697fe0390122873cb1b4ab19bdc to your computer and use it in GitHub Desktop.
LocalStorage servise
This file contains hidden or 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
enum LocalStorageExpired { | |
INFINITE = 'INFINITE', | |
LOGOUT = 'LOGOUT', | |
} | |
class LocalStorageService { | |
prefix = 'GG_'; | |
get<T extends unknown>(key: string, defaultValue: T): T { | |
try { | |
const sting = localStorage.getItem(this.prefix + key); | |
if (!sting) { | |
return defaultValue; | |
} | |
return JSON.parse(sting).v || defaultValue; | |
} catch { | |
} | |
return defaultValue; | |
} | |
set(key: string, value: unknown, isClearAfterLogout: boolean = false) { | |
localStorage.setItem( | |
key, | |
JSON.stringify({ | |
v: value, | |
exp: isClearAfterLogout ? LocalStorageExpired.LOGOUT : LocalStorageExpired.INFINITE, | |
}), | |
); | |
} | |
remove(key: string) { | |
localStorage.removeItem(key); | |
} | |
isTypeExpired(key: string, type: LocalStorageExpired) { | |
try { | |
const sting = localStorage.getItem(this.prefix + key); | |
if (!sting) { | |
return false; | |
} | |
return JSON.parse(sting).exp === type; | |
} catch { | |
} | |
return false; | |
} | |
clearLogout() { | |
Object.keys(localStorage).forEach(key => { | |
if (key.slice(0, this.prefix.length) === this.prefix) { | |
if (this.isTypeExpired(key, LocalStorageExpired.LOGOUT)) { | |
this.remove(key); | |
} | |
} | |
}); | |
} | |
} | |
export default new LocalStorageService(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment