UNPKG

2.03 kBJavaScriptView Raw
1/* global __webpack_dev_server_client__ */
2import WebSocketClient from "./clients/WebSocketClient.js";
3import { log } from "./utils/log.js"; // this WebsocketClient is here as a default fallback, in case the client is not injected
4
5/* eslint-disable camelcase */
6
7var Client = // eslint-disable-next-line no-nested-ternary
8typeof __webpack_dev_server_client__ !== "undefined" ? typeof __webpack_dev_server_client__.default !== "undefined" ? __webpack_dev_server_client__.default : __webpack_dev_server_client__ : WebSocketClient;
9/* eslint-enable camelcase */
10
11var retries = 0;
12var maxRetries = 10; // Initialized client is exported so external consumers can utilize the same instance
13// It is mutable to enforce singleton
14// eslint-disable-next-line import/no-mutable-exports
15
16export var client = null;
17/**
18 * @param {string} url
19 * @param {{ [handler: string]: (data?: any, params?: any) => any }} handlers
20 * @param {number} [reconnect]
21 */
22
23var socket = function initSocket(url, handlers, reconnect) {
24 client = new Client(url);
25 client.onOpen(function () {
26 retries = 0;
27
28 if (typeof reconnect !== "undefined") {
29 maxRetries = reconnect;
30 }
31 });
32 client.onClose(function () {
33 if (retries === 0) {
34 handlers.close();
35 } // Try to reconnect.
36
37
38 client = null; // After 10 retries stop trying, to prevent logspam.
39
40 if (retries < maxRetries) {
41 // Exponentially increase timeout to reconnect.
42 // Respectfully copied from the package `got`.
43 // eslint-disable-next-line no-restricted-properties
44 var retryInMs = 1000 * Math.pow(2, retries) + Math.random() * 100;
45 retries += 1;
46 log.info("Trying to reconnect...");
47 setTimeout(function () {
48 socket(url, handlers, reconnect);
49 }, retryInMs);
50 }
51 });
52 client.onMessage(
53 /**
54 * @param {any} data
55 */
56 function (data) {
57 var message = JSON.parse(data);
58
59 if (handlers[message.type]) {
60 handlers[message.type](message.data, message.params);
61 }
62 });
63};
64
65export default socket;
\No newline at end of file