refactor(storage-manager): namespace as key, values as object properties

This commit is contained in:
Sarah Vaupel 2019-11-26 17:53:03 +01:00 committed by Gregor Kleen
parent 610d13a729
commit 42dd41f9d6

View File

@ -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);
}
}