UNPKG

@trap_stevo/legendarybuilderproreact-ui

Version:

The legendary UI & utility API that makes your application a legendary application. ~ Created by Steven Compton

217 lines 8.74 kB
import _slicedToArray from "@babel/runtime/helpers/slicedToArray"; import _defineProperty from "@babel/runtime/helpers/defineProperty"; import _classCallCheck from "@babel/runtime/helpers/classCallCheck"; import _createClass from "@babel/runtime/helpers/createClass"; function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; } function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; } import cronParser from "cron-parser"; import io from "socket.io-client"; var HUDIoTide = /*#__PURE__*/function () { function HUDIoTide() { var maxReconnectionAttempts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 5; var maxReconnectDelay = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 10000; _classCallCheck(this, HUDIoTide); this.maxReconnectAttempts = maxReconnectionAttempts; this.maxReconnectionDelay = maxReconnectDelay; this.reconnectAttempts = 0; this.errorCallback = null; this.eventHandlers = {}; this.sockets = {}; } _createClass(HUDIoTide, [{ key: "setErrorCallback", value: function setErrorCallback(callback) { this.errorCallback = callback; } }, { key: "createIO", value: function createIO(socketName, url) { var _this = this; var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; if (this.sockets[socketName]) { console.error("Connection ~ ".concat(socketName, " already exists.")); return; } var socket = io(url, _objectSpread(_objectSpread({}, options), {}, { reconnectionAttempts: this.maxReconnectAttempts, reconnectionDelayMax: this.maxReconnectionDelay, transports: ["websocket"] })); this.sockets[socketName] = socket; socket.on("connect", function () { console.log("".concat(socketName, " connected to ").concat(url)); _this.reconnectAttempts = 0; }); socket.on("disconnect", function () { console.log("".concat(socketName, " disconnected from ").concat(url)); }); socket.on("connect_error", function (error) { _this.handleError(socketName, error); }); socket.on("reconnect_attempt", function () { _this.reconnectAttempts += 1; console.log("Reconnection attempt ".concat(_this.reconnectAttempts, " for ").concat(socketName)); }); socket.on("reconnect_failed", function () { _this.handleError(socketName, new Error("Did not reconnect to ".concat(socketName, " after ").concat(_this.maxReconnectAttempts, " attempts!"))); }); if (this.eventHandlers[socketName]) { for (var _i = 0, _Object$entries = Object.entries(this.eventHandlers[socketName]); _i < _Object$entries.length; _i++) { var _Object$entries$_i = _slicedToArray(_Object$entries[_i], 2), event = _Object$entries$_i[0], handler = _Object$entries$_i[1]; socket.on(event, handler); } } } }, { key: "emitEvent", value: function emitEvent(socketName, event, data) { if (!this.sockets[socketName]) { this.handleError(socketName, new Error("Connection ~ ".concat(socketName, " does not exist."))); return; } this.sockets[socketName].emit(event, data); } }, { key: "onEvent", value: function onEvent(socketName, event, handler) { if (!this.sockets[socketName]) { if (!this.eventHandlers[socketName]) { this.eventHandlers[socketName] = {}; } this.eventHandlers[socketName][event] = handler; return; } this.sockets[socketName].on(event, handler); } }, { key: "scheduleEventEmit", value: function scheduleEventEmit(socketName, event, data, interval) { var _this2 = this; if (!this.sockets[socketName]) { this.handleError(socketName, new Error("Connection ~ ".concat(socketName, " does not exist."))); return; } setInterval(function () { _this2.sockets[socketName].emit(event, data); }, interval); } }, { key: "scheduleAdvancedEventEmit", value: function scheduleAdvancedEventEmit(socketName, event, data, cronExpression) { var _this3 = this; if (!this.sockets[socketName]) { this.handleError(socketName, new Error("Connection ~ ".concat(socketName, " does not exist."))); return; } var interval = cronParser.parseExpression(cronExpression); var executeTask = function executeTask() { var next = interval.next().getTime() - Date.now(); if (next > 0) { _this3.scheduledTasks[socketName] = setTimeout(function () { _this3.sockets[socketName].emit(event, data); executeTask(); }, next); } }; executeTask(); } }, { key: "useMiddleware", value: function useMiddleware(socketName, middleware) { var _this4 = this; if (!this.sockets[socketName]) { this.handleError(socketName, new Error("Connection ~ ".concat(socketName, " does not exist."))); return; } var socket = this.sockets[socketName]; socket.use(function (packet, next) { try { middleware(packet, next); } catch (error) { _this4.handleError(socketName, error); } }); } }, { key: "setAuthToken", value: function setAuthToken(socketName, token) { if (!this.sockets[socketName]) { this.handleError(socketName, new Error("Connection ~ ".concat(socketName, " does not exist."))); return; } this.sockets[socketName].io.opts.query = { token: token }; } }, { key: "closeSocket", value: function closeSocket(socketName) { if (!this.sockets[socketName]) { this.handleError(socketName, new Error("Connection ~ ".concat(socketName, " does not exist."))); return; } this.sockets[socketName].close(); delete this.sockets[socketName]; delete this.eventHandlers[socketName]; } }, { key: "enableLogging", value: function enableLogging(socketName) { if (!this.sockets[socketName]) { this.handleError(socketName, new Error("Connection ~ ".concat(socketName, " does not exist."))); return; } var socket = this.sockets[socketName]; socket.onAny(function (event) { for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { args[_key - 1] = arguments[_key]; } console.log("[".concat(socketName, "] Event: ").concat(event, ", Args:"), args); }); } }, { key: "cacheEvent", value: function cacheEvent(socketName, event, data) { if (!this.sockets[socketName]) { this.handleError(socketName, new Error("Connection ~ ".concat(socketName, " does not exist."))); return; } var cachedEvents = JSON.parse(localStorage.getItem("".concat(socketName, "_cache")) || "[]"); cachedEvents.push({ event: event, data: data, timestamp: Date.now() }); localStorage.setItem("".concat(socketName, "_cache"), JSON.stringify(cachedEvents)); } }, { key: "syncCachedEvents", value: function syncCachedEvents(socketName) { var _this5 = this; if (!this.sockets[socketName]) { this.handleError(socketName, new Error("Connection ~ ".concat(socketName, " does not exist."))); return; } var cachedEvents = JSON.parse(localStorage.getItem("".concat(socketName, "_cache")) || "[]"); cachedEvents.forEach(function (_ref) { var event = _ref.event, data = _ref.data; _this5.sockets[socketName].emit(event, data); }); localStorage.removeItem("".concat(socketName, "_cache")); } }, { key: "handleError", value: function handleError(socketName, error) { if (this.errorCallback) { this.errorCallback(socketName, error); return; } console.error("Error in ".concat(socketName, ": "), error); } }]); return HUDIoTide; }(); export default HUDIoTide;