Created
July 6, 2020 15:03
-
-
Save difosfor/373da4b9ea92149fe85591b0cf4d91b4 to your computer and use it in GitHub Desktop.
Typed localStorage
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
export class TypedStorage<Items> { | |
private prefix: string; | |
constructor(prefix: string) { | |
this.prefix = prefix; | |
} | |
public delete<Key extends keyof Items>(key: Key) { | |
const value = this.get(key); | |
const prefixedKey = this.getPrefixedKey(key); | |
localStorage.removeItem(prefixedKey); | |
return value; | |
} | |
public get<Key extends keyof Items>(key: Key, defaultValue?: Items[Key]) { | |
const prefixedKey = this.getPrefixedKey(key); | |
const value = localStorage.getItem(prefixedKey); | |
return value === null ? defaultValue : JSON.parse(value); | |
} | |
public set<Key extends keyof Items>(key: Key, value: Items[Key]) { | |
const prefixedKey = this.getPrefixedKey(key); | |
try { | |
localStorage.setItem(prefixedKey, JSON.stringify(value)); | |
} catch (error) { | |
console.log(`Failed to persist ${prefixedKey} in localStorage`, error); | |
} | |
} | |
private getPrefixedKey<Key extends keyof Items>(key: Key) { | |
return `${this.prefix}${key}`; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment