-
Notifications
You must be signed in to change notification settings - Fork 69
/
Copy pathfrontend-lib.js
113 lines (89 loc) · 3.08 KB
/
frontend-lib.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
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
/* eslint-disable */
/* Event Emitter */
const eventify = (self) => {
self.events = {};
self.on = function (event, listener) {
if (typeof self.events[event] !== 'object') {
self.events[event] = []
}
self.events[event].push(listener)
};
self.removeListener = function (event, listener) {
let idx;
if (typeof self.events[event] === 'object') {
idx = self.events[event].indexOf(listener);
if (idx > -1) {
self.events[event].splice(idx, 1)
}
}
};
self.emit = function (event) {
let i, listeners, length, args = [].slice.call(arguments, 1);
if (typeof self.events[event] === 'object') {
listeners = self.events[event].slice();
length = listeners.length;
for (i = 0; i < length; i++) {
listeners[i].apply(self, args)
}
}
};
self.once = function (event, listener) {
self.on(event, function g () {
self.removeListener(event, g);
listener.apply(self, arguments)
})
};
};
const getQueryVariable = variable => {
const query = window.location.search.substring(1);
const vars = query.split('&');
for (let i = 0; i < vars.length; i++) {
const pair = vars[i].split('=');
if (decodeURIComponent(pair[0]) === variable) {
return decodeURIComponent(pair[1]);
}
}
console.log('Query variable %s not found', variable);
};
const PB = {};
eventify(PB);
PB.toAbsoluteUrl = (convertUrl, baseUrl) => {
baseUrl = baseUrl || getQueryVariable('backend');
if (!convertUrl || !convertUrl.startsWith('/cache')) {
return convertUrl;
}
const httpBackendUrl = baseUrl.replace('ws://', 'http://').replace('wss://', 'https://');
const components = httpBackendUrl.split('/');
return components[0] + '//' + components[2] + convertUrl;
};
PB.start = function(url) {
this.backend = getQueryVariable('backend') || url;
console.log('[PB] Connecting to ws backend on ' + this.backend);
const connect = () => {
this.socket = new WebSocket(this.backend);
this.emit('statusChange', 'CONNECTING');
this.socket.onopen = () => {
this.emit('statusChange', 'CONNECTED');
console.log('[PB] Connection established!')
};
this.socket.onclose = () => {
this.emit('statusChange', 'CLOSED');
setTimeout(connect, 500);
console.log('[PB] Attempt reconnect in 500ms');
};
this.socket.onerror = () => {
this.emit('statusChange', 'ERROR');
};
this.socket.onmessage = msg => {
const data = JSON.parse(msg.data);
// Maybe check if heartbeat arrives regularly to assure that connection is alive?
if (data.eventType) {
this.emit(data.eventType, data);
} else {
console.log('[PB] Unexpected packet format: ' + JSON.stringify(data));
}
};
};
connect();
};
Window.PB = PB;