Skip to content

Instantly share code, notes, and snippets.

@vv13
Created Nov 30, 2021
Embed
What would you like to do?
[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