From 42dd41f9d6109f891024c1f11cb637c246f8f315 Mon Sep 17 00:00:00 2001 From: Sarah Vaupel Date: Tue, 26 Nov 2019 17:53:03 +0100 Subject: [PATCH] refactor(storage-manager): namespace as key, values as object properties --- .../lib/storage-manager/storage-manager.js | 37 ++++++++++++------- 1 file changed, 23 insertions(+), 14 deletions(-) diff --git a/frontend/src/lib/storage-manager/storage-manager.js b/frontend/src/lib/storage-manager/storage-manager.js index 0735286c1..cb82a0006 100644 --- a/frontend/src/lib/storage-manager/storage-manager.js +++ b/frontend/src/lib/storage-manager/storage-manager.js @@ -14,10 +14,6 @@ export class StorageManager { this.namespace = namespace; } - toNamespace(key) { - return this.namespace + '--' + key; - } - save(key, value, options) { if (!key) { throw new Error('StorageManager.save called with invalid key'); @@ -30,9 +26,10 @@ export class StorageManager { const lifetime = options && options.lifetime !== undefined ? options.lifetime : LIFETIME.INFINITE; switch (lifetime) { - case LIFETIME.INFINITE: - localStorage.setItem(this.toNamespace(key), JSON.stringify(value)); + case LIFETIME.INFINITE: { + this.saveToLocalStorage({ ...this.getFromLocalStorage(), [key]: value }); break; + } default: console.error('StorageManager.save cannot save item with unsupported lifetime'); } @@ -46,17 +43,29 @@ export class StorageManager { const lifetime = options && options.lifetime !== undefined ? options.lifetime : LIFETIME.INFINITE; switch (lifetime) { - case LIFETIME.INFINITE: { - const value = JSON.parse(localStorage.getItem(this.toNamespace(key))); - if (value === null) { - // remove item from localStorage if it stores an invalid value (cannot be parsed) - localStorage.removeItem(this.toNamespace(key)); - } - return value; - } + 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); + } + }