Re-add persistence

This commit is contained in:
Philipp Heckel 2022-02-24 15:17:47 -05:00
parent fef46823eb
commit 0958c1d527
3 changed files with 24 additions and 18 deletions

View file

@ -1,42 +1,41 @@
import {topicUrl} from "./utils";
import Subscription from "./Subscription";
import Subscriptions from "./Subscriptions";
export class Repository {
loadSubscriptions() {
console.log(`[Repository] Loading subscriptions from localStorage`);
const subscriptions = {};
const rawSubscriptions = localStorage.getItem('subscriptions');
if (rawSubscriptions === null) {
return {};
}
const subscriptions = new Subscriptions();
const serialized = localStorage.getItem('subscriptions');
if (serialized === null) return subscriptions;
try {
const serializedSubscriptions = JSON.parse(rawSubscriptions);
const serializedSubscriptions = JSON.parse(serialized);
serializedSubscriptions.forEach(s => {
const subscription = new Subscription(s.baseUrl, s.topic);
subscription.notifications = s.notifications;
subscriptions[topicUrl(s.baseUrl, s.topic)] = subscription;
subscription.addNotifications(s.notifications);
subscriptions.add(subscription);
});
console.log(`[Repository] Loaded ${subscriptions.size()} subscription(s) from localStorage`);
return subscriptions;
} catch (e) {
console.log("LocalStorage", `Unable to deserialize subscriptions: ${e.message}`)
return {};
console.log(`[Repository] Unable to deserialize subscriptions: ${e.message}`);
return subscriptions;
}
}
saveSubscriptions(subscriptions) {
return;
console.log(`[Repository] Saving subscriptions ${subscriptions} to localStorage`);
console.log(`[Repository] Saving ${subscriptions.size()} subscription(s) to localStorage`);
const serializedSubscriptions = Object.keys(subscriptions).map(k => {
const subscription = subscriptions[k];
const serialized = JSON.stringify(subscriptions.map( (id, subscription) => {
return {
baseUrl: subscription.baseUrl,
topic: subscription.topic,
notifications: subscription.notifications
notifications: subscription.getNotifications(),
last: subscription.last
}
});
localStorage.setItem('subscriptions', JSON.stringify(serializedSubscriptions));
}));
localStorage.setItem('subscriptions', serialized);
}
}

View file

@ -42,6 +42,10 @@ class Subscriptions {
return first;
}
size() {
return this.subscriptions.size;
}
clone() {
const c = new Subscriptions();
c.subscriptions = new Map(this.subscriptions);

View file

@ -153,6 +153,9 @@ const App = () => {
const toggleDrawer = () => {
setDrawerOpen(!drawerOpen);
};
useEffect(() => {
setSubscriptions(repository.loadSubscriptions());
}, [/* initial render only */]);
useEffect(() => {
connectionManager.refresh(subscriptions, handleNotification);
repository.saveSubscriptions(subscriptions);