-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbrowser-websocket.ts
More file actions
43 lines (38 loc) · 1.23 KB
/
browser-websocket.ts
File metadata and controls
43 lines (38 loc) · 1.23 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
import { ObservableResources, SubscriptionSocket } from "../src/"
export class BrowserSubscriptionClientWebsocket<
ServerResources extends ObservableResources = any,
ClientResources extends ObservableResources = any
> extends SubscriptionSocket<ClientResources, ServerResources> {
private websocket: WebSocket
private messageQueue: Array<string> = []
private isConnected: boolean = false
constructor(
url: string,
resources: ClientResources,
onError: (error: any) => void,
onClose: () => void,
protocols?: string | Array<string>
) {
super(
onError,
() => {
this.messageQueue = []
this.isConnected = false
onClose()
},
resources
)
this.websocket = new WebSocket(url, protocols)
this.websocket.addEventListener('open', () => {
this.isConnected = true
this.messageQueue.forEach(message => this.send(message))
})
}
protected send(message: string): void {
if(this.isConnected) {
this.websocket.send(JSON.stringify(message))
} else {
this.messageQueue.push(message)
}
}
}