Skip to content

Instantly share code, notes, and snippets.

@fadi-george
Created November 14, 2023 21:40
Show Gist options
  • Save fadi-george/9043bc4afe20ed12432685a5d58dfc17 to your computer and use it in GitHub Desktop.
Save fadi-george/9043bc4afe20ed12432685a5d58dfc17 to your computer and use it in GitHub Desktop.
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