This repository was archived by the owner on Sep 8, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 49
/
Copy pathSocket.js
66 lines (53 loc) · 1.44 KB
/
Socket.js
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
var module = angular.module('App');
module.factory('Socket', (Stream, $rootScope) => {
class Socket {
constructor(url) {
this.url = url;
this.queue = [];
this.open();
}
setupQueryStream() {
// opening a socket === async and a queue may form
this.socket.onopen = () => this.flush();
if (!this.queryStream) {
this.queryStream = new Stream();
this.queryStream.listen( (data) => {
// Stringify now in case data changes while waiting in this.queue
data = JSON.stringify(data);
if (this.socket.readyState === WebSocket.OPEN) {
this.send(data);
} else {
this.queue.push(data);
if (this.socket.readyState === WebSocket.CLOSE)
this.open();
}
});
}
}
setupEventStream() {
this.eventStream = this.eventStream || new Stream();
this.socket.onmesssage = (data) => {
// Now Entering AngularJS...
$rootScope.$apply( () => this.eventStream.push( JSON.parse(data) ));
};
}
close() {
this.socket.close();
}
open() {
this.socket = new WebSocket(this.url);
this.setupQueryStream();
this.setupEventStream();
}
send(data) {
return this.socket.send( data );
}
flush() {
while (item = this.queue.pop()) {
this.send(item);
}
}
}
// Singleton
return new Socket('/api');
});