]> git.r.bdr.sh - rbdr/forum/blame - src/socket_coordinator.js
Update translations
[rbdr/forum] / src / socket_coordinator.js
CommitLineData
7372fe18 1import EventEmitter from 'eventemitter3';
38416066
BB
2import { socketServer } from './config/config';
3
4const internals = {
5
7372fe18
BB
6 kReconnectInterval: 3000, // How often we attempt to reconnect
7
8 eventEmitter: new EventEmitter(), // internal event emitter
38416066 9 socket: null, // stores the socket connection
7372fe18 10 retry: null, // stores the retry operation
38416066
BB
11
12 connect() {
13
7372fe18 14 console.debug('Connecting socket.');
38416066 15 internals.socket = new WebSocket(socketServer);
7372fe18
BB
16
17 internals.socket.addEventListener('message', internals.onMessage);
18 internals.socket.addEventListener('error', internals.onError);
19 internals.socket.addEventListener('close', internals.onClose);
20 },
21
22 // Handles socket errors.
23
24 onError(event) {
25
26 console.error('Socket error. Closing connection');
27 internals.socket.close();
28 },
29
30 // Handles socket errors.
31
32 onClose(event) {
33
34 console.debug(`Connection closed: ${event.reason || 'Unknown reason'}. Retrying in ${internals.kReconnectInterval}ms`);
35
36 internals.retry && clearTimeout(internals.retry);
37 internals.retry = setTimeout(() => {
38
39 console.debug('Reconnecting socket.');
40 internals.retry = null;
41 internals.connect();
42 }, internals.kReconnectInterval);
43 },
44
45 // Forwards events from the socket to our internal event emitter.
46
47 onMessage(event) {
48
49 internals.eventEmitter.emit('message', event);
38416066
BB
50 }
51};
52
53export const onMessage = function (listener) {
54
55 if (!internals.socket) {
56 internals.connect();
57 }
58
7372fe18 59 internals.eventEmitter.on('message', (message) => {
38416066
BB
60
61 listener(JSON.parse(message.data));
62 });
63};