UNPKG

1.07 kBJavaScriptView Raw
1'use strict';
2
3var SockJS = require('sockjs-client/dist/sockjs');
4
5var retries = 0;
6var sock = null;
7
8var socket = function initSocket(url, handlers) {
9 sock = new SockJS(url);
10
11 sock.onopen = function onopen() {
12 retries = 0;
13 };
14
15 sock.onclose = function onclose() {
16 if (retries === 0) {
17 handlers.close();
18 } // Try to reconnect.
19
20
21 sock = null; // After 10 retries stop trying, to prevent logspam.
22
23 if (retries <= 10) {
24 // Exponentially increase timeout to reconnect.
25 // Respectfully copied from the package `got`.
26 // eslint-disable-next-line no-mixed-operators, no-restricted-properties
27 var retryInMs = 1000 * Math.pow(2, retries) + Math.random() * 100;
28 retries += 1;
29 setTimeout(function () {
30 socket(url, handlers);
31 }, retryInMs);
32 }
33 };
34
35 sock.onmessage = function onmessage(e) {
36 // This assumes that all data sent via the websocket is JSON.
37 var msg = JSON.parse(e.data);
38
39 if (handlers[msg.type]) {
40 handlers[msg.type](msg.data);
41 }
42 };
43};
44
45module.exports = socket;
\No newline at end of file