feat(storage-manager): add storage manager library
This commit is contained in:
parent
169a4799b4
commit
1023240136
62
frontend/src/lib/storage-manager/storage-manager.js
Normal file
62
frontend/src/lib/storage-manager/storage-manager.js
Normal 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');
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
Loading…
Reference in New Issue
Block a user