@intuitionrobotics/thunderstorm
Version:
98 lines • 3.07 kB
JavaScript
import { merge, Module } from "@intuitionrobotics/ts-common";
import { ThunderDispatcher } from "../core/thunder-dispatcher.js";
export class StorageModule_Class extends Module {
cache = {};
constructor() {
super("StorageModule");
}
init() {
window.addEventListener('storage', this.handleStorageEvent);
}
handleStorageEvent = (e) => {
const dispatcher = new ThunderDispatcher('__onStorageKeyEvent');
dispatcher.dispatchUI(e);
dispatcher.dispatchModule(e);
};
getStorage = (persist) => persist ? localStorage : sessionStorage;
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?.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?.match(query)) {
localStorage.removeItem(key);
}
}
}
}
export const StorageModule = new StorageModule_Class();
//TODO Generic Keys like in the tests contexts
export class StorageKey {
key;
persist;
constructor(key, persist = true) {
this.key = key;
this.persist = persist;
}
get(defaultValue) {
// @ts-expect-error TS struggles with this dynamic typing
return StorageModule.get(this.key, defaultValue, this.persist);
}
patch(value) {
const previousValue = this.get();
const mergedValue = merge(previousValue, value);
this.set(mergedValue);
return mergedValue;
}
set(value) {
// @ts-expect-error TS struggles with this dynamic typing
StorageModule.set(this.key, value, this.persist);
return value;
}
delete() {
StorageModule.delete(this.key, this.persist);
}
clearCache() {
StorageModule.clearCache(this.key);
}
}
//# sourceMappingURL=StorageModule.js.map