#What do they do?
- Adds a prefix to storage keys
- Handle JSON encoding/decoding for simple JSON object storage
- Handle Null values
#Local Storage Service
Data in localStorage does not expire.
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
class LocalStorageService { | |
private readonly storagePrefix = "scratchy__" | |
get<T>(key: string): T | null { | |
const item = window.localStorage.getItem(this.storagePrefix + key); | |
if (!item || item === "null") { | |
return null; | |
} | |
try { | |
return JSON.parse(item); | |
} catch (e) { | |
console.log(e); | |
} | |
return null; | |
} | |
set(key: string, value: any): boolean { | |
if (value === undefined) { | |
value = null; | |
} else { | |
value = JSON.stringify(value); | |
} | |
try { | |
window.localStorage.setItem(this.storagePrefix + key, value); | |
} catch (e) { | |
console.log(e); | |
} | |
return false; | |
} | |
remove(key: string) { | |
window.localStorage.removeItem(this.storagePrefix + key); | |
} | |
} | |
export default new LocalStorageService(); |
#Session Storage Service
Data in sessionStorage is cleared when the page session ends.
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
class SessionStorageService { | |
private readonly storagePrefix = "scratchy__" | |
get<T>(key: string): T | null { | |
const item = window.sessionStorage.getItem(this.storagePrefix + key); | |
if (!item || item === "null") { | |
return null; | |
} | |
try { | |
return JSON.parse(item); | |
} catch (e) { | |
console.log(e); | |
} | |
return null; | |
} | |
set(key: string, value: any): boolean { | |
if (value === undefined) { | |
value = null; | |
} else { | |
value = JSON.stringify(value); | |
} | |
try { | |
window.sessionStorage.setItem(this.storagePrefix + key, value); | |
} catch (e) { | |
console.log(e); | |
} | |
return false; | |
} | |
remove(key: string) { | |
window.sessionStorage.removeItem(this.storagePrefix + key); | |
} | |
} | |
export default new SessionStorageService(); |