-
Notifications
You must be signed in to change notification settings - Fork 381
Expand file tree
/
Copy pathchannels.ts
More file actions
152 lines (125 loc) · 3.56 KB
/
channels.ts
File metadata and controls
152 lines (125 loc) · 3.56 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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
import { isFalse, isNil, isNotNil } from '../utils'
import { getUrlWithPrefix } from './instance'
type ChannelCallback<TData = any> = (data: TData) => void
export type EventSourceChannel = <TData = any>(
topic: string,
callback?: ChannelCallback<TData>,
) => Channel
export interface Channel {
subscribe: () => void
unsubscribe: () => void
}
const DELAY_AND_RECONNECT = 20000
const DELAY_AND_RETRY = 3000
class EventSourceConnection {
channels = new Map<string, Optional<(e: MessageEvent) => void>>()
eventSource: Optional<EventSource>
timerId: Optional<number>
source: string
delay: number = DELAY_AND_RECONNECT
constructor(source: string, delay?: number) {
this.source = source
this.delay = delay ?? this.delay
this.setEventSource()
}
listen(eventSource: EventSource): void {
eventSource.addEventListener('error', (e: MessageEvent) => {
this.reconnect(DELAY_AND_RETRY)
})
eventSource.addEventListener('ping', (e: MessageEvent) => {
this.reconnect(this.delay)
})
}
cleanup(): void {
this.channels.forEach((handler, topic) => {
if (isNotNil(handler)) {
this.eventSource?.removeEventListener(topic, handler)
}
})
this.eventSource?.close()
this.eventSource = undefined
}
resubscribe(): void {
this.channels.forEach((handler, topic) => {
if (isNotNil(handler)) {
this.eventSource?.addEventListener(topic, handler)
}
})
}
reconnect(delay: number): void {
clearTimeout(this.timerId as number)
this.timerId = setTimeout(() => {
console.log(`Reconnecting Event Source ${this.source}`)
this.cleanup()
this.setEventSource()
this.resubscribe()
}, delay) as unknown as number
}
getEventSource(): EventSource {
return new EventSource(this.source, {
withCredentials: true,
})
}
setEventSource(): void {
this.eventSource = this.getEventSource()
this.listen(this.eventSource)
}
addChannel<TData = any>(
topic: string,
callback: ChannelCallback<TData>,
): void {
const handler = this.getChannelHandler(topic, callback)
this.eventSource?.addEventListener(topic, handler)
this.channels.set(topic, handler)
}
removeChannel(topic: string): void {
const handler = this.getChannel(topic)
if (isNotNil(handler)) {
this.eventSource?.removeEventListener(topic, handler)
this.channels.delete(topic)
}
}
hasChannel(topic: string): boolean {
return isNotNil(this.getChannel(topic))
}
getChannel(topic: string): Optional<(e: MessageEvent) => void> {
return this.channels.get(topic)
}
private getChannelHandler<TData = any>(
topic: string,
callback: ChannelCallback<TData>,
): (e: MessageEvent) => void {
return (event: MessageEvent<string>) => {
this.reconnect(this.delay)
if (isNil(topic) || isNil(callback) || isNil(event.data)) return
try {
callback(JSON.parse(event.data))
} catch (error) {
console.warn(error)
}
}
}
}
let Connection: EventSourceConnection
export function useChannelEvents(): <TData = any>(
topic: string,
callback?: ChannelCallback<TData>,
) => Channel {
if (isNil(Connection)) {
Connection = new EventSourceConnection(getUrlWithPrefix('/api/events'))
}
return (topic, callback) => ({
subscribe() {
if (
isNotNil(topic) &&
isNotNil(callback) &&
isFalse(Connection.hasChannel(topic))
) {
Connection.addChannel(topic, callback)
}
},
unsubscribe() {
Connection.removeChannel(topic)
},
})
}