socket.js 2.0 KB

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