socket.js 1.1 KB

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