Created
November 14, 2023 21:40
-
-
Save fadi-george/9043bc4afe20ed12432685a5d58dfc17 to your computer and use it in GitHub Desktop.
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 StorageHelper { | |
private storage: Storage; | |
private tempStorage: Record<string, string> = {}; | |
public isStorageAvailable: boolean; | |
constructor(storage: "sessionStorage" | "localStorage") { | |
this.storage = window[storage]; | |
this.isStorageAvailable = this.checkIfStorageAvailable(); | |
} | |
private checkIfStorageAvailable() { | |
try { | |
const test = "__storage_test__"; | |
this.storage.setItem(test, test); | |
this.storage.removeItem(test); | |
return true; | |
} catch (e) { | |
return false; | |
} | |
} | |
public setItem(key: string, value: string) { | |
if (this.isStorageAvailable) { | |
this.storage.setItem(key, value); | |
} else { | |
this.tempStorage[key] = value; | |
} | |
} | |
public getItem(key: string) { | |
if (this.isStorageAvailable) { | |
return this.storage.getItem(key); | |
} else { | |
return this.tempStorage[key]; | |
} | |
} | |
public removeItem(key: string) { | |
if (this.isStorageAvailable) { | |
this.storage.removeItem(key); | |
} else { | |
delete this.tempStorage[key]; | |
} | |
} | |
public clear() { | |
if (this.isStorageAvailable) { | |
this.storage.clear(); | |
} else { | |
this.tempStorage = {}; | |
} | |
} | |
} | |
export const sessionStorageHelper = new StorageHelper("sessionStorage"); | |
export const localStorageHelper = new StorageHelper("localStorage"); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment