UNPKG

redux-ws-middleware

Version:

This package makes web socket management much easier with redux

3 lines (2 loc) 11.8 kB
"use strict";function e(e,n){var t=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);n&&(r=r.filter((function(n){return Object.getOwnPropertyDescriptor(e,n).enumerable}))),t.push.apply(t,r)}return t}function n(e,n){if(!(e instanceof n))throw new TypeError("Cannot call a class as a function")}function t(e,n){for(var t=0;t<n.length;t++){var r=n[t];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}function r(e,n,r){return n&&t(e.prototype,n),r&&t(e,r),Object.defineProperty(e,"prototype",{writable:!1}),e}function o(e,n,t){return n in e?Object.defineProperty(e,n,{value:t,enumerable:!0,configurable:!0,writable:!0}):e[n]=t,e}function i(e,n){if("function"!=typeof n&&null!==n)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(n&&n.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),n&&u(e,n)}function c(e){return c=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)},c(e)}function u(e,n){return u=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,n){return e.__proto__=n,e},u(e,n)}function a(e,n){if(null==e)return{};var t,r,o=function(e,n){if(null==e)return{};var t,r,o={},i=Object.keys(e);for(r=0;r<i.length;r++)t=i[r],n.indexOf(t)>=0||(o[t]=e[t]);return o}(e,n);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);for(r=0;r<i.length;r++)t=i[r],n.indexOf(t)>=0||Object.prototype.propertyIsEnumerable.call(e,t)&&(o[t]=e[t])}return o}function s(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function l(e,n){if(n&&("object"==typeof n||"function"==typeof n))return n;if(void 0!==n)throw new TypeError("Derived constructors may only return object or undefined");return s(e)}function f(e){var n=function(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(e){return!1}}();return function(){var t,r=c(e);if(n){var o=c(this).constructor;t=Reflect.construct(r,arguments,o)}else t=r.apply(this,arguments);return l(this,t)}}function d(e,n){return function(e){if(Array.isArray(e))return e}(e)||function(e,n){var t=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null==t)return;var r,o,i=[],c=!0,u=!1;try{for(t=t.call(e);!(c=(r=t.next()).done)&&(i.push(r.value),!n||i.length!==n);c=!0);}catch(e){u=!0,o=e}finally{try{c||null==t.return||t.return()}finally{if(u)throw o}}return i}(e,n)||v(e,n)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function v(e,n){if(e){if("string"==typeof e)return p(e,n);var t=Object.prototype.toString.call(e).slice(8,-1);return"Object"===t&&e.constructor&&(t=e.constructor.name),"Map"===t||"Set"===t?Array.from(e):"Arguments"===t||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t)?p(e,n):void 0}}function p(e,n){(null==n||n>e.length)&&(n=e.length);for(var t=0,r=new Array(n);t<n;t++)r[t]=e[t];return r}var h,y=r((function e(){var t=this;n(this,e),o(this,"prefix","redux-ws-middleware"),o(this,"log",(function(e,n){console.groupCollapsed("[".concat(t.prefix,"] ").concat(e)),n&&console.log(n),console.groupEnd()})),o(this,"error",(function(e,n){console.error("[".concat(t.prefix,"] ").concat(e),n)}))})),b=r((function e(t){var r=this,i=t.debug;n(this,e),o(this,"loggerService",void 0),o(this,"log",(function(e,n){var t;null===(t=r.loggerService)||void 0===t||t.log(e,n)})),o(this,"error",(function(e,n){var t;null===(t=r.loggerService)||void 0===t||t.error(e,n)})),i&&(this.loggerService=new y)})),g=function(e){i(c,b);var t=f(c);function c(e){var r,i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1e3,u=arguments.length>2?arguments[2]:void 0;return n(this,c),o(s(r=t.call(this,{debug:u})),"interval",void 0),o(s(r),"callback",void 0),o(s(r),"reconnections",0),o(s(r),"timeout",null),o(s(r),"startJob",(function(){var e=r.getInterval();r.log("Reconnect in ".concat(e,"ms")),r.timeout=setTimeout(r.callback,e),r.incrementReconnections()})),o(s(r),"removeJob",(function(){r.timeout&&(clearTimeout(r.timeout),r.timeout=null),r.resetReconnections()})),o(s(r),"getInterval",(function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:r.interval;if("number"==typeof e)return e;if(!e.length)return 0;var n=e.length-1;return r.reconnections<=n?e[r.reconnections]:e[n]})),o(s(r),"setReconnections",(function(e){r.reconnections=e})),o(s(r),"incrementReconnections",(function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:r.reconnections;r.setReconnections(e+1)})),o(s(r),"resetReconnections",(function(){r.setReconnections(0)})),r.interval=i,r.callback=e,r}return r(c)}();!function(e){e[e.CONNECTED=0]="CONNECTED",e[e.DISCONNECTED=1]="DISCONNECTED"}(h||(h={}));var O,S,E=r((function t(r,i){var c=this;n(this,t),o(this,"actionTypes",void 0),o(this,"dispatch",void 0),o(this,"getDispatch",(function(){return c.dispatch})),o(this,"dispatchConnected",(function(){c.dispatch({type:c.actionTypes[h.CONNECTED]})})),o(this,"dispatchDisconnected",(function(n){c.dispatch(function(n){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?e(Object(r),!0).forEach((function(e){o(n,e,r[e])})):Object.getOwnPropertyDescriptors?Object.defineProperties(n,Object.getOwnPropertyDescriptors(r)):e(Object(r)).forEach((function(e){Object.defineProperty(n,e,Object.getOwnPropertyDescriptor(r,e))}))}return n}({type:c.actionTypes[h.DISCONNECTED]},n?{payload:n}:{}))})),this.actionTypes=r,this.dispatch=i})),w=r((function e(t,r){var i=this;n(this,e),o(this,"serializer",void 0),o(this,"deserializer",void 0),o(this,"serialize",(function(e){var n,t=(null===(n=i.serializer)||void 0===n?void 0:n.call(i,e))||e;return"string"==typeof t?t:JSON.stringify(t)})),o(this,"deserialize",(function(e){var n,t;try{t=JSON.parse(e)}catch(n){t=e}return(null===(n=i.deserializer)||void 0===n?void 0:n.call(i,t))||t})),this.serializer=t,this.deserializer=r})),m=function(e){i(c,b);var t=f(c);function c(e){var r;return n(this,c),o(s(r=t.call(this,{debug:e})),"queue",[]),o(s(r),"getValues",(function(){return r.queue.map((function(e){return JSON.parse(e)}))})),o(s(r),"add",(function(e){var n=r.getUniqueRequest(e);n&&(r.queue.push(n),r.log("Added to queue",e))})),o(s(r),"remove",(function(e){var n=JSON.stringify(e);r.queue=r.queue.filter((function(e){return e!==n})),r.log("Removed from queue",e)})),o(s(r),"clear",(function(){r.queue=[],r.log("Queue cleared")})),o(s(r),"getUniqueRequest",(function(e){var n=JSON.stringify(e);return r.queue.includes(n)?(r.log("Already in queue",e),null):n})),r}return r(c)}();!function(e){e.OPEN="open",e.ERROR="error",e.CLOSE="close",e.MESSAGE="message"}(O||(O={})),function(e){e[e.FORCE_CLOSE=1005]="FORCE_CLOSE"}(S||(S={}));var R=["shouldReconnect","reconnectionInterval","debug","serialize","deserialize"],C=function(e){i(c,b);var t=f(c);function c(e,r,i){var u;n(this,c),o(s(u=t.call(this,{debug:e.debug})),"options",void 0),o(s(u),"shouldReconnect",void 0),o(s(u),"reconnectService",void 0),o(s(u),"reduxService",void 0),o(s(u),"serializerService",void 0),o(s(u),"queueService",void 0),o(s(u),"ws",null),o(s(u),"open",(function(){if("undefined"!=typeof window&&!u.ws){var e=u.options,n=e.url,t=e.protocols;u.ws=new WebSocket(n,t),u.setListeners()}})),o(s(u),"send",(function(e){var n;if(u.checkOpenStateAndOpenConnection(e)){var t=u.serializerService.serialize(e);null===(n=u.ws)||void 0===n||n.send(t),u.log("Sent",t)}})),o(s(u),"close",(function(e){var n;u.checkOpenStateAndThrowError(),null===(n=u.ws)||void 0===n||n.close(e)})),o(s(u),"setListeners",(function(){u.ws&&(u.ws.addEventListener(O.OPEN,u.handleOpen),u.ws.addEventListener(O.MESSAGE,u.handleMessage),u.ws.addEventListener(O.ERROR,u.handleError),u.ws.addEventListener(O.CLOSE,u.handleClose))})),o(s(u),"removeListeners",(function(){u.ws&&(u.ws.removeEventListener(O.OPEN,u.handleOpen),u.ws.removeEventListener(O.MESSAGE,u.handleMessage),u.ws.removeEventListener(O.ERROR,u.handleError),u.ws.removeEventListener(O.CLOSE,u.handleClose))})),o(s(u),"handleOpen",(function(e){u.log("Connected"),u.reduxService.dispatchConnected(),u.reconnectService.removeJob(),u.sendQueuedRequests()})),o(s(u),"handleMessage",(function(e){var n,t,r=u.serializerService.deserialize(e.data);u.log("Received",r),u.options.onMessage(r,u.reduxService.getDispatch()),null!==(n=(t=u.options).shouldClose)&&void 0!==n&&n.call(t,r)&&u.close(S.FORCE_CLOSE)})),o(s(u),"handleError",(function(e){u.error("Error",e)})),o(s(u),"handleClose",(function(e){var n=e.code,t=e.reason,r=n===S.FORCE_CLOSE;u.log("Disconnected",{code:n,reason:t,forceDisconnection:r}),u.reduxService.dispatchDisconnected({reason:t,forceDisconnection:r,code:n}),u.removeListeners(),u.ws=null,u.checkReconnectAbilityAndStartJob(e,r)})),o(s(u),"sendQueuedRequests",(function(){var e=u.queueService.getValues();if(e.length){var n,t=function(e,n){var t="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!t){if(Array.isArray(e)||(t=v(e))||n&&e&&"number"==typeof e.length){t&&(e=t);var r=0,o=function(){};return{s:o,n:function(){return r>=e.length?{done:!0}:{done:!1,value:e[r++]}},e:function(e){throw e},f:o}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var i,c=!0,u=!1;return{s:function(){t=t.call(e)},n:function(){var e=t.next();return c=e.done,e},e:function(e){u=!0,i=e},f:function(){try{c||null==t.return||t.return()}finally{if(u)throw i}}}}(e);try{for(t.s();!(n=t.n()).done;){var r=n.value;u.send(r),u.queueService.remove(r)}}catch(e){t.e(e)}finally{t.f()}}})),o(s(u),"checkReconnectAbilityAndStartJob",(function(e,n){n&&"boolean"==typeof u.shouldReconnect||("boolean"!=typeof u.shouldReconnect?u.shouldReconnect(e)&&u.reconnectService.startJob():u.reconnectService.startJob())})),o(s(u),"checkOpenStateAndOpenConnection",(function(e){if(u.isReadyStateOpen())return!0;if(!u.options.shouldOpen)throw new Error("WebSocket is not connected. Make sure it is connected before triggering an action.");return"boolean"==typeof u.options.shouldOpen||u.options.shouldOpen(e)?(u.queueService.add(e),u.open(),!1):void 0})),o(s(u),"checkOpenStateAndThrowError",(function(){if(!u.isReadyStateOpen())throw new Error("WebSocket is not connected. Make sure it is connected before triggering an action.")})),o(s(u),"isReadyStateOpen",(function(){var e;return(null===(e=u.ws)||void 0===e?void 0:e.readyState)===WebSocket.OPEN||!1}));var l=e.shouldReconnect,f=e.reconnectionInterval,d=e.debug,p=e.serialize,h=e.deserialize,y=a(e,R);return u.options=y,u.shouldReconnect=null==l||l,u.reconnectService=new g(u.open,f,d),u.reduxService=new E(i,r),u.serializerService=new w(p,h),u.queueService=new m(d),!1!==e.autoConnect&&u.open(),d&&u.log("Debug mode is ENABLED",e),u}return r(c)}(),j=["actionTypes","completedActionTypes"],A=function(e){var n=e instanceof RegExp;return function(t){return n?e.test(t):t===e}};exports.createSocketMiddleware=function(e){var n=e.actionTypes,t=e.completedActionTypes,r=a(e,j),o=d(n,3),i=o[0],c=o[1],u=o[2],s=A(i),l=c?A(c):null,f=u?A(u):null;return function(e){var n=e.dispatch,o=new C(r,n,t);return function(e){return function(n){var t,r;(null!=l&&l(n.type)&&o.open(),null!=f&&f(n.type))&&o.close((null===(t=n.data)||void 0===t?void 0:t.code)||(null===(r=n.payload)||void 0===r?void 0:r.code)||n.code);return s(n.type)&&o.send(n.data||n.payload),e(n)}}}}; //# sourceMappingURL=index.cjs.js.map