diff --git a/frontend/src/lib/storage-manager/storage-manager.js b/frontend/src/lib/storage-manager/storage-manager.js new file mode 100644 index 000000000..0735286c1 --- /dev/null +++ b/frontend/src/lib/storage-manager/storage-manager.js @@ -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'); + } + } + +}