]> git.r.bdr.sh - rbdr/forum/blob - app/socket_coordinator.js
f8fb52512a806db7c99e8a6e62ba01e04c9df365
[rbdr/forum] / app / socket_coordinator.js
1 import EventEmitter from 'eventemitter3';
2 import { socketServer } from './config/config';
3
4 const internals = {
5
6 kReconnectInterval: 3000, // How often we attempt to reconnect
7
8 eventEmitter: new EventEmitter(), // internal event emitter
9 socket: null, // stores the socket connection
10 retry: null, // stores the retry operation
11
12 connect() {
13
14 console.debug('Connecting socket.');
15 internals.socket = new WebSocket(socketServer);
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);
50 }
51 };
52
53 export const onMessage = function (listener) {
54
55 if (!internals.socket) {
56 internals.connect();
57 }
58
59 internals.eventEmitter.on('message', (message) => {
60
61 listener(JSON.parse(message.data));
62 });
63 };