@intuitionrobotics/thunderstorm
Version:
101 lines • 3.39 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.StorageKey = exports.StorageModule = exports.StorageModule_Class = void 0;
const ts_common_1 = require("@intuitionrobotics/ts-common");
const thunder_dispatcher_1 = require("../core/thunder-dispatcher");
class StorageModule_Class extends ts_common_1.Module {
constructor() {
super("StorageModule");
this.cache = {};
this.handleStorageEvent = (e) => {
const dispatcher = new thunder_dispatcher_1.ThunderDispatcher('__onStorageKeyEvent');
dispatcher.dispatchUI(e);
dispatcher.dispatchModule(e);
};
this.getStorage = (persist) => persist ? localStorage : sessionStorage;
}
init() {
window.addEventListener('storage', this.handleStorageEvent);
}
set(key, value, persist = true) {
if (!value)
return this.delete(key);
this.cache[key] = value;
this.getStorage(persist).setItem(key, JSON.stringify(value));
}
delete(key, persist = true) {
this.clearCache(key);
this.getStorage(persist).removeItem(key);
}
clearCache(key) {
delete this.cache[key];
}
get(key, defaultValue, persist = true) {
let value = this.cache[key];
if (value)
return value;
value = this.getStorage(persist).getItem(key);
// this.logDebug(`get: ${key} = ${value}`)
if (!value)
return defaultValue || null;
return this.cache[key] = JSON.parse(value);
}
query(query) {
const toRet = [];
for (let i = 0; i < localStorage.length; i++) {
const key = localStorage.key(i);
if (key === null || key === void 0 ? void 0 : key.match(query)) {
const item = localStorage.getItem(key);
if (item) {
try {
const exp = JSON.parse(item);
toRet.push(exp);
}
catch (e) {
}
}
}
}
return toRet;
}
deleteAll(query) {
for (let i = 0; i < localStorage.length; i++) {
const key = localStorage.key(i);
if (key === null || key === void 0 ? void 0 : key.match(query)) {
localStorage.removeItem(key);
}
}
}
}
exports.StorageModule_Class = StorageModule_Class;
exports.StorageModule = new StorageModule_Class();
//TODO Generic Keys like in the tests contexts
class StorageKey {
constructor(key, persist = true) {
this.key = key;
this.persist = persist;
}
get(defaultValue) {
// @ts-ignore
return exports.StorageModule.get(this.key, defaultValue, this.persist);
}
patch(value) {
const previousValue = this.get();
const mergedValue = (0, ts_common_1.merge)(previousValue, value);
this.set(mergedValue);
return mergedValue;
}
set(value) {
// @ts-ignore
exports.StorageModule.set(this.key, value, this.persist);
return value;
}
delete() {
exports.StorageModule.delete(this.key, this.persist);
}
clearCache() {
exports.StorageModule.clearCache(this.key);
}
}
exports.StorageKey = StorageKey;
//# sourceMappingURL=StorageModule.js.map