bigbluebutton-Github/bigbluebutton-html5/imports/ui/services/storage/reactive.js

75 lines
1.7 KiB
JavaScript
Raw Normal View History

2016-07-07 20:50:07 +08:00
import { Tracker } from 'meteor/tracker';
import { EJSON } from 'meteor/ejson';
import { isObject, isArray, isString } from 'radash';
2016-07-07 20:50:07 +08:00
// Reactive wrapper for browser Storage's
export default class StorageTracker {
constructor(storage, prefix = '') {
2017-06-03 03:25:02 +08:00
if (!(storage instanceof Storage)) {
throw `Expecting a instanceof Storage receive a '${storage.constructor.name}' instance`;
2016-07-07 20:50:07 +08:00
}
this._trackers = {};
this._prefix = prefix;
this._storage = storage;
}
_ensureDeps(key) {
if (!this._trackers[key]) {
2017-06-03 03:25:02 +08:00
this._trackers[key] = new Tracker.Dependency();
2016-07-07 20:50:07 +08:00
}
}
_prefixedKey(key) {
2016-07-12 00:28:55 +08:00
key = key.replace(this._prefix, '');
2016-07-07 20:50:07 +08:00
return `${this._prefix}${key}`;
}
key(n) {
return this._storage.key(n);
}
getItem(key) {
2017-06-03 03:25:02 +08:00
const prefixedKey = this._prefixedKey(key);
2016-07-12 00:28:55 +08:00
this._ensureDeps(prefixedKey);
2016-07-12 03:42:54 +08:00
this._trackers[prefixedKey].depend();
2016-07-07 20:50:07 +08:00
2016-07-12 00:28:55 +08:00
let value = this._storage.getItem(prefixedKey);
2016-07-07 20:50:07 +08:00
2023-02-21 21:24:40 +08:00
if (value && isString(value)) {
2016-07-07 20:50:07 +08:00
try {
value = EJSON.parse(value);
} catch (e) {}
}
return value;
}
setItem(key, value) {
2017-06-03 03:25:02 +08:00
const prefixedKey = this._prefixedKey(key);
2016-07-12 00:28:55 +08:00
this._ensureDeps(prefixedKey);
if (isObject(value) || isArray(value)) {
2016-07-07 20:50:07 +08:00
value = EJSON.stringify(value);
}
2016-07-12 00:28:55 +08:00
this._storage.setItem(prefixedKey, value);
this._trackers[prefixedKey].changed();
2016-07-07 20:50:07 +08:00
}
removeItem(key) {
2017-06-03 03:25:02 +08:00
const prefixedKey = this._prefixedKey(key);
2016-07-12 00:28:55 +08:00
this._storage.removeItem(prefixedKey);
if (!this._trackers[prefixedKey]) return;
2016-07-12 00:28:55 +08:00
this._trackers[prefixedKey].changed();
delete this._trackers[prefixedKey];
2016-07-07 20:50:07 +08:00
}
clear() {
2017-06-03 03:25:02 +08:00
Object.keys(this._trackers).forEach((key) => {
2016-07-07 20:50:07 +08:00
this.removeItem(key);
});
}
2017-06-03 03:25:02 +08:00
}