Newer
Older
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
import Ember from 'ember';
export default Ember.Service.extend({
shouldClose: false,
init() {
this._super(...arguments);
this.debug('session', this.get('systemId'));
},
connect(systemId) {
this.set('shouldClose', false);
this.debug('setting up websocket', systemId);
const socket = new WebSocket(`ws://localhost:8080/v1/changelogstream/${systemId}`);
this.set('socket', socket);
socket.onopen = this.get('events.onOpen').bind(this);
socket.onerror = this.get('events.onError').bind(this);
socket.onmessage = this.get('events.onMessage').bind(this);
// automatically reconnect
socket.onclose = () => {
if(!this.get('shouldClose')) {
this.debug('connection lost, reconnecting!');
this.set('reconnectionTimeout', setTimeout(() => {
this.connect(systemId);
this.set('reconnectionTimeout', null);
}, 500));
}
};
// close socket connection when the user closes the window/tab or nagivates to a different website
window.onbeforeunload = this.get('disconnect').bind(this);
},
disconnect() {
this.debug('disconnect');
this.set('shouldClose', true);
this.get('socket').close();
// just in case it disconnected right before disconnect() was called.
clearTimeout(this.get('reconnectionTimeout'));
},
events: {
onError(err) {
this.debug('socket connection encountered an error', err);
},
onOpen() {
this.debug('connection established');
},
onMessage(message) {
const changelogJson = message.data;
this.debug('new changelog received', changelogJson);
try {
const changelog = JSON.parse(changelogJson);
this.debug('changelog converted', changelog);
} catch (e) {
console.error('could not parse changelog json', e, changelogJson);
}
}
}
});