const LIFETIME = { INFINITE: 'infinite', }; export class StorageManager { namespace; constructor(namespace) { if (!namespace) { throw new Error('Cannot setup StorageManager without namespace'); } this.namespace = namespace; } save(key, value, options) { if (!key) { throw new Error('StorageManager.save called with invalid key'); } if (options && options.lifetime !== undefined && !Object.values(LIFETIME).includes(options.lifetime)) { throw new Error('StorageManager.save called with unsupported lifetime option'); } const lifetime = options && options.lifetime !== undefined ? options.lifetime : LIFETIME.INFINITE; switch (lifetime) { case LIFETIME.INFINITE: { this.saveToLocalStorage({ ...this.getFromLocalStorage(), [key]: value }); break; } default: console.error('StorageManager.save cannot save item with unsupported lifetime'); } } load(key, options) { if (options && options.lifetime !== undefined && !Object.values(LIFETIME).includes(options.lifetime)) { throw new Error('StorageManager.load called with unsupported lifetime option'); } const lifetime = options && options.lifetime !== undefined ? options.lifetime : LIFETIME.INFINITE; switch (lifetime) { case LIFETIME.INFINITE: return this.getFromLocalStorage()[key]; default: console.error('StorageManager.load cannot load item with unsupported lifetime'); } } getFromLocalStorage() { const state = JSON.parse(window.localStorage.getItem(this.namespace)); if (state === null) { // remove item from localStorage if it stores an invalid value (cannot be parsed) this.clearLocalStorage(); return {}; } return state; } saveToLocalStorage(value) { window.localStorage.setItem(this.namespace, JSON.stringify(value)); } clearLocalStorage() { window.localStorage.removeItem(this.namespace); } }