redux-ws-middleware
Version:
This package makes web socket management much easier with redux
858 lines (635 loc) • 25.2 kB
JavaScript
function ownKeys(object, enumerableOnly) {
var keys = Object.keys(object);
if (Object.getOwnPropertySymbols) {
var symbols = Object.getOwnPropertySymbols(object);
enumerableOnly && (symbols = symbols.filter(function (sym) {
return Object.getOwnPropertyDescriptor(object, sym).enumerable;
})), keys.push.apply(keys, symbols);
}
return keys;
}
function _objectSpread2(target) {
for (var i = 1; i < arguments.length; i++) {
var source = null != arguments[i] ? arguments[i] : {};
i % 2 ? ownKeys(Object(source), !0).forEach(function (key) {
_defineProperty(target, key, source[key]);
}) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) {
Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
});
}
return target;
}
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ("value" in descriptor) descriptor.writable = true;
Object.defineProperty(target, descriptor.key, descriptor);
}
}
function _createClass(Constructor, protoProps, staticProps) {
if (protoProps) _defineProperties(Constructor.prototype, protoProps);
if (staticProps) _defineProperties(Constructor, staticProps);
Object.defineProperty(Constructor, "prototype", {
writable: false
});
return Constructor;
}
function _defineProperty(obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
}
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function");
}
subClass.prototype = Object.create(superClass && superClass.prototype, {
constructor: {
value: subClass,
writable: true,
configurable: true
}
});
Object.defineProperty(subClass, "prototype", {
writable: false
});
if (superClass) _setPrototypeOf(subClass, superClass);
}
function _getPrototypeOf(o) {
_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) {
return o.__proto__ || Object.getPrototypeOf(o);
};
return _getPrototypeOf(o);
}
function _setPrototypeOf(o, p) {
_setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) {
o.__proto__ = p;
return o;
};
return _setPrototypeOf(o, p);
}
function _isNativeReflectConstruct() {
if (typeof Reflect === "undefined" || !Reflect.construct) return false;
if (Reflect.construct.sham) return false;
if (typeof Proxy === "function") return true;
try {
Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {}));
return true;
} catch (e) {
return false;
}
}
function _objectWithoutPropertiesLoose(source, excluded) {
if (source == null) return {};
var target = {};
var sourceKeys = Object.keys(source);
var key, i;
for (i = 0; i < sourceKeys.length; i++) {
key = sourceKeys[i];
if (excluded.indexOf(key) >= 0) continue;
target[key] = source[key];
}
return target;
}
function _objectWithoutProperties(source, excluded) {
if (source == null) return {};
var target = _objectWithoutPropertiesLoose(source, excluded);
var key, i;
if (Object.getOwnPropertySymbols) {
var sourceSymbolKeys = Object.getOwnPropertySymbols(source);
for (i = 0; i < sourceSymbolKeys.length; i++) {
key = sourceSymbolKeys[i];
if (excluded.indexOf(key) >= 0) continue;
if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue;
target[key] = source[key];
}
}
return target;
}
function _assertThisInitialized(self) {
if (self === void 0) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}
return self;
}
function _possibleConstructorReturn(self, call) {
if (call && (typeof call === "object" || typeof call === "function")) {
return call;
} else if (call !== void 0) {
throw new TypeError("Derived constructors may only return object or undefined");
}
return _assertThisInitialized(self);
}
function _createSuper(Derived) {
var hasNativeReflectConstruct = _isNativeReflectConstruct();
return function _createSuperInternal() {
var Super = _getPrototypeOf(Derived),
result;
if (hasNativeReflectConstruct) {
var NewTarget = _getPrototypeOf(this).constructor;
result = Reflect.construct(Super, arguments, NewTarget);
} else {
result = Super.apply(this, arguments);
}
return _possibleConstructorReturn(this, result);
};
}
function _slicedToArray(arr, i) {
return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest();
}
function _arrayWithHoles(arr) {
if (Array.isArray(arr)) return arr;
}
function _iterableToArrayLimit(arr, i) {
var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"];
if (_i == null) return;
var _arr = [];
var _n = true;
var _d = false;
var _s, _e;
try {
for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) {
_arr.push(_s.value);
if (i && _arr.length === i) break;
}
} catch (err) {
_d = true;
_e = err;
} finally {
try {
if (!_n && _i["return"] != null) _i["return"]();
} finally {
if (_d) throw _e;
}
}
return _arr;
}
function _unsupportedIterableToArray(o, minLen) {
if (!o) return;
if (typeof o === "string") return _arrayLikeToArray(o, minLen);
var n = Object.prototype.toString.call(o).slice(8, -1);
if (n === "Object" && o.constructor) n = o.constructor.name;
if (n === "Map" || n === "Set") return Array.from(o);
if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);
}
function _arrayLikeToArray(arr, len) {
if (len == null || len > arr.length) len = arr.length;
for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];
return arr2;
}
function _nonIterableRest() {
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 _createForOfIteratorHelper(o, allowArrayLike) {
var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"];
if (!it) {
if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") {
if (it) o = it;
var i = 0;
var F = function () {};
return {
s: F,
n: function () {
if (i >= o.length) return {
done: true
};
return {
done: false,
value: o[i++]
};
},
e: function (e) {
throw e;
},
f: F
};
}
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 normalCompletion = true,
didErr = false,
err;
return {
s: function () {
it = it.call(o);
},
n: function () {
var step = it.next();
normalCompletion = step.done;
return step;
},
e: function (e) {
didErr = true;
err = e;
},
f: function () {
try {
if (!normalCompletion && it.return != null) it.return();
} finally {
if (didErr) throw err;
}
}
};
}
var PREFIX = 'redux-ws-middleware';
var LoggerService = /*#__PURE__*/_createClass(function LoggerService() {
var _this = this;
_classCallCheck(this, LoggerService);
_defineProperty(this, "prefix", PREFIX);
_defineProperty(this, "log", function (message, data) {
console.groupCollapsed("[".concat(_this.prefix, "] ").concat(message));
if (data) console.log(data);
console.groupEnd();
});
_defineProperty(this, "error", function (message, data) {
console.error("[".concat(_this.prefix, "] ").concat(message), data);
});
});
var BaseService = /*#__PURE__*/_createClass(function BaseService(_ref) {
var _this = this;
var debug = _ref.debug;
_classCallCheck(this, BaseService);
_defineProperty(this, "loggerService", void 0);
_defineProperty(this, "log", function (message, data) {
var _this$loggerService;
(_this$loggerService = _this.loggerService) === null || _this$loggerService === void 0 ? void 0 : _this$loggerService.log(message, data);
});
_defineProperty(this, "error", function (message, data) {
var _this$loggerService2;
(_this$loggerService2 = _this.loggerService) === null || _this$loggerService2 === void 0 ? void 0 : _this$loggerService2.error(message, data);
});
if (!debug) return;
this.loggerService = new LoggerService();
});
var ReconnectService = /*#__PURE__*/function (_BaseService) {
_inherits(ReconnectService, _BaseService);
var _super = _createSuper(ReconnectService);
function ReconnectService(callback) {
var _this;
var _interval = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1000;
var debug = arguments.length > 2 ? arguments[2] : undefined;
_classCallCheck(this, ReconnectService);
_this = _super.call(this, {
debug: debug
});
_defineProperty(_assertThisInitialized(_this), "interval", void 0);
_defineProperty(_assertThisInitialized(_this), "callback", void 0);
_defineProperty(_assertThisInitialized(_this), "reconnections", 0);
_defineProperty(_assertThisInitialized(_this), "timeout", null);
_defineProperty(_assertThisInitialized(_this), "startJob", function () {
var interval = _this.getInterval();
_this.log("Reconnect in ".concat(interval, "ms"));
_this.timeout = setTimeout(_this.callback, interval);
_this.incrementReconnections();
});
_defineProperty(_assertThisInitialized(_this), "removeJob", function () {
if (_this.timeout) {
clearTimeout(_this.timeout);
_this.timeout = null;
}
_this.resetReconnections();
});
_defineProperty(_assertThisInitialized(_this), "getInterval", function () {
var interval = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : _this.interval;
if (typeof interval === 'number') return interval;
if (!interval.length) return 0;
var lastIntervalsIdx = interval.length - 1;
if (_this.reconnections <= lastIntervalsIdx) {
return interval[_this.reconnections];
}
return interval[lastIntervalsIdx];
});
_defineProperty(_assertThisInitialized(_this), "setReconnections", function (value) {
_this.reconnections = value;
});
_defineProperty(_assertThisInitialized(_this), "incrementReconnections", function () {
var start = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : _this.reconnections;
_this.setReconnections(start + 1);
});
_defineProperty(_assertThisInitialized(_this), "resetReconnections", function () {
_this.setReconnections(0);
});
_this.interval = _interval;
_this.callback = callback;
return _this;
}
return _createClass(ReconnectService);
}(BaseService);
var SocketActionType;
(function (SocketActionType) {
SocketActionType[SocketActionType["CONNECTED"] = 0] = "CONNECTED";
SocketActionType[SocketActionType["DISCONNECTED"] = 1] = "DISCONNECTED";
})(SocketActionType || (SocketActionType = {}));
var ReduxService = /*#__PURE__*/_createClass(function ReduxService(actionTypes, dispatch) {
var _this = this;
_classCallCheck(this, ReduxService);
_defineProperty(this, "actionTypes", void 0);
_defineProperty(this, "dispatch", void 0);
_defineProperty(this, "getDispatch", function () {
return _this.dispatch;
});
_defineProperty(this, "dispatchConnected", function () {
_this.dispatch({
type: _this.actionTypes[SocketActionType.CONNECTED]
});
});
_defineProperty(this, "dispatchDisconnected", function (payload) {
_this.dispatch(_objectSpread2({
type: _this.actionTypes[SocketActionType.DISCONNECTED]
}, payload ? {
payload: payload
} : {}));
});
this.actionTypes = actionTypes;
this.dispatch = dispatch;
});
var SerializerService = /*#__PURE__*/_createClass(function SerializerService(serializer, deserializer) {
var _this = this;
_classCallCheck(this, SerializerService);
_defineProperty(this, "serializer", void 0);
_defineProperty(this, "deserializer", void 0);
_defineProperty(this, "serialize", function (data) {
var _this$serializer;
var serializedData = ((_this$serializer = _this.serializer) === null || _this$serializer === void 0 ? void 0 : _this$serializer.call(_this, data)) || data;
return typeof serializedData === 'string' ? serializedData : JSON.stringify(serializedData);
});
_defineProperty(this, "deserialize", function (data) {
var _this$deserializer;
var parsedData;
try {
parsedData = JSON.parse(data);
} catch (_unused) {
parsedData = data;
}
return ((_this$deserializer = _this.deserializer) === null || _this$deserializer === void 0 ? void 0 : _this$deserializer.call(_this, parsedData)) || parsedData;
});
this.serializer = serializer;
this.deserializer = deserializer;
});
var QueueService = /*#__PURE__*/function (_BaseService) {
_inherits(QueueService, _BaseService);
var _super = _createSuper(QueueService);
function QueueService(debug) {
var _this;
_classCallCheck(this, QueueService);
_this = _super.call(this, {
debug: debug
});
_defineProperty(_assertThisInitialized(_this), "queue", []);
_defineProperty(_assertThisInitialized(_this), "getValues", function () {
return _this.queue.map(function (value) {
return JSON.parse(value);
});
});
_defineProperty(_assertThisInitialized(_this), "add", function (data) {
var uniqueRequest = _this.getUniqueRequest(data);
if (!uniqueRequest) return;
_this.queue.push(uniqueRequest);
_this.log('Added to queue', data);
});
_defineProperty(_assertThisInitialized(_this), "remove", function (data) {
var stringifyRequest = JSON.stringify(data);
_this.queue = _this.queue.filter(function (value) {
return value !== stringifyRequest;
});
_this.log('Removed from queue', data);
});
_defineProperty(_assertThisInitialized(_this), "clear", function () {
_this.queue = [];
_this.log('Queue cleared');
});
_defineProperty(_assertThisInitialized(_this), "getUniqueRequest", function (data) {
var stringifyRequest = JSON.stringify(data);
var existingRequest = _this.queue.includes(stringifyRequest);
if (existingRequest) {
_this.log('Already in queue', data);
return null;
}
return stringifyRequest;
});
return _this;
}
return _createClass(QueueService);
}(BaseService);
var WebSocketEvent;
(function (WebSocketEvent) {
WebSocketEvent["OPEN"] = "open";
WebSocketEvent["ERROR"] = "error";
WebSocketEvent["CLOSE"] = "close";
WebSocketEvent["MESSAGE"] = "message";
})(WebSocketEvent || (WebSocketEvent = {}));
var WebSocketClosingCode;
(function (WebSocketClosingCode) {
WebSocketClosingCode[WebSocketClosingCode["FORCE_CLOSE"] = 1005] = "FORCE_CLOSE";
})(WebSocketClosingCode || (WebSocketClosingCode = {}));
var _excluded$1 = ["shouldReconnect", "reconnectionInterval", "debug", "serialize", "deserialize"];
var WebSocketService = /*#__PURE__*/function (_BaseService) {
_inherits(WebSocketService, _BaseService);
var _super = _createSuper(WebSocketService);
function WebSocketService(options, dispatch, actionTypes) {
var _this;
_classCallCheck(this, WebSocketService);
_this = _super.call(this, {
debug: options.debug
});
_defineProperty(_assertThisInitialized(_this), "options", void 0);
_defineProperty(_assertThisInitialized(_this), "shouldReconnect", void 0);
_defineProperty(_assertThisInitialized(_this), "reconnectService", void 0);
_defineProperty(_assertThisInitialized(_this), "reduxService", void 0);
_defineProperty(_assertThisInitialized(_this), "serializerService", void 0);
_defineProperty(_assertThisInitialized(_this), "queueService", void 0);
_defineProperty(_assertThisInitialized(_this), "ws", null);
_defineProperty(_assertThisInitialized(_this), "open", function () {
if (typeof window === 'undefined' || _this.ws) return;
var _this$options = _this.options,
url = _this$options.url,
protocols = _this$options.protocols;
_this.ws = new WebSocket(url, protocols);
_this.setListeners();
});
_defineProperty(_assertThisInitialized(_this), "send", function (req) {
var _this$ws;
var isOpen = _this.checkOpenStateAndOpenConnection(req);
if (!isOpen) return;
var message = _this.serializerService.serialize(req);
(_this$ws = _this.ws) === null || _this$ws === void 0 ? void 0 : _this$ws.send(message);
_this.log('Sent', message);
});
_defineProperty(_assertThisInitialized(_this), "close", function (code) {
var _this$ws2;
_this.checkOpenStateAndThrowError();
(_this$ws2 = _this.ws) === null || _this$ws2 === void 0 ? void 0 : _this$ws2.close(code);
});
_defineProperty(_assertThisInitialized(_this), "setListeners", function () {
if (!_this.ws) return;
_this.ws.addEventListener(WebSocketEvent.OPEN, _this.handleOpen);
_this.ws.addEventListener(WebSocketEvent.MESSAGE, _this.handleMessage);
_this.ws.addEventListener(WebSocketEvent.ERROR, _this.handleError);
_this.ws.addEventListener(WebSocketEvent.CLOSE, _this.handleClose);
});
_defineProperty(_assertThisInitialized(_this), "removeListeners", function () {
if (!_this.ws) return;
_this.ws.removeEventListener(WebSocketEvent.OPEN, _this.handleOpen);
_this.ws.removeEventListener(WebSocketEvent.MESSAGE, _this.handleMessage);
_this.ws.removeEventListener(WebSocketEvent.ERROR, _this.handleError);
_this.ws.removeEventListener(WebSocketEvent.CLOSE, _this.handleClose);
});
_defineProperty(_assertThisInitialized(_this), "handleOpen", function (_) {
_this.log('Connected');
_this.reduxService.dispatchConnected();
_this.reconnectService.removeJob();
_this.sendQueuedRequests();
});
_defineProperty(_assertThisInitialized(_this), "handleMessage", function (event) {
var _this$options$shouldC, _this$options2;
var data = _this.serializerService.deserialize(event.data);
_this.log('Received', data);
_this.options.onMessage(data, _this.reduxService.getDispatch());
if ((_this$options$shouldC = (_this$options2 = _this.options).shouldClose) !== null && _this$options$shouldC !== void 0 && _this$options$shouldC.call(_this$options2, data)) {
_this.close(WebSocketClosingCode.FORCE_CLOSE);
}
});
_defineProperty(_assertThisInitialized(_this), "handleError", function (event) {
_this.error('Error', event);
});
_defineProperty(_assertThisInitialized(_this), "handleClose", function (event) {
var code = event.code,
reason = event.reason;
var forceDisconnection = code === WebSocketClosingCode.FORCE_CLOSE;
_this.log('Disconnected', {
code: code,
reason: reason,
forceDisconnection: forceDisconnection
});
_this.reduxService.dispatchDisconnected({
reason: reason,
forceDisconnection: forceDisconnection,
code: code
});
_this.removeListeners();
_this.ws = null;
_this.checkReconnectAbilityAndStartJob(event, forceDisconnection);
});
_defineProperty(_assertThisInitialized(_this), "sendQueuedRequests", function () {
var queue = _this.queueService.getValues();
if (!queue.length) return;
var _iterator = _createForOfIteratorHelper(queue),
_step;
try {
for (_iterator.s(); !(_step = _iterator.n()).done;) {
var req = _step.value;
_this.send(req);
_this.queueService.remove(req);
}
} catch (err) {
_iterator.e(err);
} finally {
_iterator.f();
}
});
_defineProperty(_assertThisInitialized(_this), "checkReconnectAbilityAndStartJob", function (event, forceDisconnection) {
if (forceDisconnection && typeof _this.shouldReconnect === 'boolean') return;
if (typeof _this.shouldReconnect === 'boolean') {
_this.reconnectService.startJob();
return;
}
if (_this.shouldReconnect(event)) {
_this.reconnectService.startJob();
}
});
_defineProperty(_assertThisInitialized(_this), "checkOpenStateAndOpenConnection", function (req) {
if (_this.isReadyStateOpen()) return true;
if (!_this.options.shouldOpen) {
throw new Error('WebSocket is not connected. Make sure it is connected before triggering an action.');
}
if (typeof _this.options.shouldOpen === 'boolean' || _this.options.shouldOpen(req)) {
_this.queueService.add(req);
_this.open();
return false;
}
});
_defineProperty(_assertThisInitialized(_this), "checkOpenStateAndThrowError", function () {
if (_this.isReadyStateOpen()) return;
throw new Error('WebSocket is not connected. Make sure it is connected before triggering an action.');
});
_defineProperty(_assertThisInitialized(_this), "isReadyStateOpen", function () {
var _this$ws3;
return ((_this$ws3 = _this.ws) === null || _this$ws3 === void 0 ? void 0 : _this$ws3.readyState) === WebSocket.OPEN || false;
});
var shouldReconnect = options.shouldReconnect,
reconnectionInterval = options.reconnectionInterval,
debug = options.debug,
serialize = options.serialize,
deserialize = options.deserialize,
restOptions = _objectWithoutProperties(options, _excluded$1);
_this.options = restOptions;
_this.shouldReconnect = shouldReconnect !== null && shouldReconnect !== void 0 ? shouldReconnect : true;
_this.reconnectService = new ReconnectService(_this.open, reconnectionInterval, debug);
_this.reduxService = new ReduxService(actionTypes, dispatch);
_this.serializerService = new SerializerService(serialize, deserialize);
_this.queueService = new QueueService(debug);
if (options.autoConnect !== false) {
_this.open();
}
if (debug) {
_this.log('Debug mode is ENABLED', options);
}
return _this;
}
return _createClass(WebSocketService);
}(BaseService);
var _excluded = ["actionTypes", "completedActionTypes"];
var getTypeCheck = function getTypeCheck(actionType) {
var isRegExp = actionType instanceof RegExp;
return function (type) {
return isRegExp ? actionType.test(type) : type === actionType;
};
};
var createSocketMiddleware = function createSocketMiddleware(_ref) {
var actionTypes = _ref.actionTypes,
completedActionTypes = _ref.completedActionTypes,
socketOptions = _objectWithoutProperties(_ref, _excluded);
var _actionTypes = _slicedToArray(actionTypes, 3),
sendType = _actionTypes[0],
connectType = _actionTypes[1],
disconnectType = _actionTypes[2];
var isSend = getTypeCheck(sendType);
var isConnect = connectType ? getTypeCheck(connectType) : null;
var isDisconnect = disconnectType ? getTypeCheck(disconnectType) : null;
return function (_ref2) {
var dispatch = _ref2.dispatch;
var socket = new WebSocketService(socketOptions, dispatch, completedActionTypes);
return function (next) {
return function (action) {
if (isConnect !== null && isConnect !== void 0 && isConnect(action.type)) {
socket.open();
}
if (isDisconnect !== null && isDisconnect !== void 0 && isDisconnect(action.type)) {
var _action$data, _action$payload;
socket.close(((_action$data = action.data) === null || _action$data === void 0 ? void 0 : _action$data.code) || ((_action$payload = action.payload) === null || _action$payload === void 0 ? void 0 : _action$payload.code) || action.code);
}
if (isSend(action.type)) {
socket.send(action.data || action.payload);
}
return next(action);
};
};
};
};
export { createSocketMiddleware };
//# sourceMappingURL=index.esm.mjs.map