Skip to content

Instantly share code, notes, and snippets.

@vv13
Created November 30, 2021 05:10
Show Gist options
  • Save vv13/a11792e79f617cb4e46eae869c13739b to your computer and use it in GitHub Desktop.
Save vv13/a11792e79f617cb4e46eae869c13739b to your computer and use it in GitHub Desktop.
[TS] localStorage & memoryCache storage instances
abstract class CustomStorage {
abstract storage: any;
abstract getItem<T>(key: string): T | null;
abstract setItem(key: string, value: any): void;
abstract removeItem(key: string): void;
abstract clear(): void;
getItemAndDelete<T>(key: string): T | null {
const value = this.getItem<T>(key);
this.removeItem(key);
return value;
}
}
class MemoryStorageFactory extends CustomStorage {
storage: { [key: string]: any } = {};
getItem(key: string) {
return this.storage[key] || null;
}
setItem(key: string, value: any): void {
this.storage[key] = value;
}
removeItem(key: string): void {
delete this.storage[key];
}
clear(): void {
this.storage = {};
}
}
class PersistStorageFactory extends CustomStorage {
storage: { [key: string]: any } = window.localStorage;
getItem<T>(key: string): T | null {
const value = this.storage.getItem(key);
try {
return JSON.parse(value || '');
} catch {
this.removeItem(key);
return null;
}
}
setItem(key: string, value: any): void {
if (value === undefined || value === null) {
return;
}
this.storage.setItem(key, JSON.stringify(value));
}
removeItem(key: string): void {
this.storage.removeItem(key);
}
clear(): void {
this.storage.clear();
}
}
export const MemoryStorage = new MemoryStorageFactory();
export const PersistStorage = new PersistStorageFactory();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment