-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathServerEventService.ts
More file actions
34 lines (30 loc) · 1.12 KB
/
ServerEventService.ts
File metadata and controls
34 lines (30 loc) · 1.12 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
let source: EventSource | null = null;
let listeners: EventListener[] = [];
export function registerNotificationListener(eventType: string, listener: EventListener): void {
if (!source) {
source = new EventSource('/api/sse', { withCredentials: true });
console.debug(`Create SSE Connection ...`);
source.addEventListener('open', () => console.debug(`Connected to SSE.`));
}
source.addEventListener(eventType, listener);
}
export function unregisterNotificationListener(eventType: string, listener: EventListener): void {
console.info(`Unregister SSE listener`, source);
if (source) {
source.removeEventListener(eventType, listener);
const idx = listeners.indexOf(listener);
listeners.splice(idx);
if (listeners.length <= 1) {
close();
}
}
}
export function closeNotificationListeners(): void {
listeners.splice(0, listeners.length);
if (source) {
console.debug(`Try closing SSE ...`);
source.addEventListener('close', () => console.info('SSE Connection closed'));
source.close();
source = null;
}
}