40 lines
777 B
TypeScript
40 lines
777 B
TypeScript
import type { Person } from '$lib/types';
|
|
|
|
export type PersonEvent = {
|
|
person: Person;
|
|
};
|
|
|
|
export function listenToPersonEvents(onPerson: (person: Person) => void) {
|
|
let stopped = false;
|
|
let source: EventSource | null = null;
|
|
|
|
function connect() {
|
|
if (stopped) return;
|
|
source = new EventSource('/api/events');
|
|
source.onmessage = (event) => {
|
|
try {
|
|
const data = JSON.parse(event.data) as PersonEvent;
|
|
if (data.person) {
|
|
onPerson(data.person);
|
|
}
|
|
} catch (err) {
|
|
console.error('Failed to parse person event', err);
|
|
}
|
|
};
|
|
|
|
source.onerror = () => {
|
|
source?.close();
|
|
source = null;
|
|
if (stopped) return;
|
|
setTimeout(connect, 2000);
|
|
};
|
|
}
|
|
|
|
connect();
|
|
|
|
return () => {
|
|
stopped = true;
|
|
source?.close();
|
|
source = null;
|
|
};
|
|
}
|