feat(storage-manager): add storage manager library

This commit is contained in:
Sarah Vaupel 2019-11-26 16:39:47 +01:00 committed by Gregor Kleen
parent 169a4799b4
commit 1023240136

View File

@ -0,0 +1,62 @@
const LIFETIME = {
INFINITE: 'infinite',
};
export class StorageManager {
namespace;
constructor(namespace) {
if (!namespace) {
throw new Error('Cannot setup StorageManager without namespace');
}
this.namespace = namespace;
}
toNamespace(key) {
return this.namespace + '--' + key;
}
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:
localStorage.setItem(this.toNamespace(key), JSON.stringify(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: {
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;
}
default:
console.error('StorageManager.load cannot load item with unsupported lifetime');
}
}
}