WebSocketClient.js 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
  2. function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); }
  3. function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } }
  4. function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; }
  5. function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; }
  6. function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
  7. import { log } from "../utils/log.js";
  8. /** @typedef {import("../index").EXPECTED_ANY} EXPECTED_ANY */
  9. /**
  10. * @implements {CommunicationClient}
  11. */
  12. var WebSocketClient = /*#__PURE__*/function () {
  13. /**
  14. * @param {string} url url to connect
  15. */
  16. function WebSocketClient(url) {
  17. _classCallCheck(this, WebSocketClient);
  18. this.client = new WebSocket(url);
  19. this.client.onerror = function (error) {
  20. log.error(error);
  21. };
  22. }
  23. /**
  24. * @param {(...args: EXPECTED_ANY[]) => void} fn function
  25. */
  26. return _createClass(WebSocketClient, [{
  27. key: "onOpen",
  28. value: function onOpen(fn) {
  29. this.client.onopen = fn;
  30. }
  31. /**
  32. * @param {(...args: EXPECTED_ANY[]) => void} fn function
  33. */
  34. }, {
  35. key: "onClose",
  36. value: function onClose(fn) {
  37. this.client.onclose = fn;
  38. }
  39. // call f with the message string as the first argument
  40. /**
  41. * @param {(...args: EXPECTED_ANY[]) => void} fn function
  42. */
  43. }, {
  44. key: "onMessage",
  45. value: function onMessage(fn) {
  46. this.client.onmessage = function (err) {
  47. fn(err.data);
  48. };
  49. }
  50. }]);
  51. }();
  52. export { WebSocketClient as default };