refactor event system to use composables

This commit is contained in:
Hayden 2023-08-02 11:49:10 -05:00
parent 884e2c700e
commit c5c9da6a7e
No known key found for this signature in database
GPG key ID: 17CF79474E257545
2 changed files with 80 additions and 24 deletions

View file

@ -0,0 +1,67 @@
export enum ServerEvent {
LocationMutation = "location.mutation",
ItemMutation = "item.mutation",
LabelMutation = "label.mutation",
}
export type EventMessage = {
event: ServerEvent;
};
let socket: WebSocket | null = null;
const listeners = new Map<ServerEvent, (() => void)[]>();
function connect(onmessage: (m: EventMessage) => void) {
const ws = new WebSocket(`ws://${window.location.host}/api/v1/ws/events`);
ws.onopen = () => {
console.debug("connected to server");
};
ws.onclose = () => {
console.debug("disconnected from server");
setTimeout(() => {
connect(onmessage);
}, 3000);
};
ws.onerror = err => {
console.error("websocket error", err);
};
ws.onmessage = msg => {
onmessage(JSON.parse(msg.data));
};
socket = ws;
}
export function onServerEvent(event: ServerEvent, callback: () => void) {
if (socket === null) {
connect(e => {
listeners.get(e.event)?.forEach(c => c());
});
}
onMounted(() => {
if (!listeners.has(event)) {
listeners.set(event, []);
}
listeners.get(event)?.push(callback);
});
onUnmounted(() => {
const got = listeners.get(event);
if (got) {
listeners.set(
event,
got.filter(c => c !== callback)
);
}
if (listeners.get(event)?.length === 0) {
listeners.delete(event);
}
});
}

View file

@ -178,31 +178,20 @@
const locationStore = useLocationStore();
type EventMessage = {
event: string;
};
onServerEvent(ServerEvent.LabelMutation, () => {
labelStore.refresh();
});
onMounted(() => {
const ws = new WebSocket(`ws://${window.location.host}/api/v1/ws/events`);
ws.onmessage = event => {
const msg: EventMessage = JSON.parse(event.data);
console.debug("recieved event", msg);
switch (msg.event) {
case "label.mutation":
labelStore.refresh();
break;
case "location.mutation":
locationStore.refreshChildren();
locationStore.refreshParents();
break;
case "item.mutation":
// item mutations can affect locations counts
// so we need to refresh those as well
locationStore.refreshChildren();
locationStore.refreshParents();
break;
}
};
onServerEvent(ServerEvent.LocationMutation, () => {
locationStore.refreshChildren();
locationStore.refreshParents();
});
onServerEvent(ServerEvent.ItemMutation, () => {
// item mutations can affect locations counts
// so we need to refresh those as well
locationStore.refreshChildren();
locationStore.refreshParents();
});
const authCtx = useAuthContext();