diff --git a/CHANGELOG.md b/CHANGELOG.md index ff56c55..cf0e4ea 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,9 @@ +## (unreleased) + +Features: + - reconnect(): Make logging to console optional + - close(): Add reconnectDelaySeconds property to close event + ## 2.0.0 (2016-5-21) Features: diff --git a/dist/angular-websocket.js b/dist/angular-websocket.js index db99c8e..41e63ea 100644 --- a/dist/angular-websocket.js +++ b/dist/angular-websocket.js @@ -98,6 +98,7 @@ this.initialTimeout = options && options.initialTimeout || 500; // 500ms this.maxTimeout = options && options.maxTimeout || 5 * 60 * 1000; // 5 minutes this.reconnectIfNotNormalClose = options && options.reconnectIfNotNormalClose || false; + this.consoleLogReconnect = options && options.consoleLogReconnect !== undefined ? options.consoleLogReconnect : true; this.binaryType = options && options.binaryType || 'blob'; this._reconnectAttempts = 0; @@ -225,6 +226,9 @@ $WebSocket.prototype._onCloseHandler = function _onCloseHandler(event) { var self = this; + if (this.reconnectIfNotNormalClose && event.code !== this._normalCloseCode || this._reconnectableStatusCodes.indexOf(event.code) > -1) { + this.reconnect(event); + } if (self.useApplyAsync) { self.scope.$applyAsync(function () { self.notifyCloseCallbacks(event); @@ -233,9 +237,6 @@ self.notifyCloseCallbacks(event); self.safeDigest(true); } - if (this.reconnectIfNotNormalClose && event.code !== this._normalCloseCode || this._reconnectableStatusCodes.indexOf(event.code) > -1) { - this.reconnect(); - } }; $WebSocket.prototype._onErrorHandler = function _onErrorHandler(event) { @@ -327,13 +328,18 @@ return promise; }; - $WebSocket.prototype.reconnect = function reconnect() { + $WebSocket.prototype.reconnect = function reconnect(event) { this.close(); var backoffDelay = this._getBackoffDelay(++this._reconnectAttempts); var backoffDelaySeconds = backoffDelay / 1000; - console.log('Reconnecting in ' + backoffDelaySeconds + ' seconds'); + if ((typeof event === 'undefined' ? 'undefined' : _typeof(event)) === 'object') { + event.reconnectDelaySeconds = backoffDelaySeconds; + } + if (this.consoleLogReconnect) { + console.log('Reconnecting in ' + backoffDelaySeconds + ' seconds'); + } $timeout(_angular2.default.bind(this, this._connect), backoffDelay); @@ -412,4 +418,4 @@ exports.default = _angular2.default.module('ngWebSocket'); module.exports = exports['default']; -}); +}); \ No newline at end of file diff --git a/dist/angular-websocket.min.js b/dist/angular-websocket.min.js index 0d82580..38756b8 100644 --- a/dist/angular-websocket.min.js +++ b/dist/angular-websocket.min.js @@ -1,2 +1,2 @@ -!function(e,t){if("function"==typeof define&&define.amd)define(["module","exports","angular","ws"],t);else if("undefined"!=typeof exports)t(module,exports,require("angular"),require("ws"));else{var o={exports:{}};t(o,o.exports,e.angular,e.ws),e.angularWebsocket=o.exports}}(this,function(e,t,o,n){"use strict";function s(e){return e&&e.__esModule?e:{"default":e}}function r(e,t,o,n){function s(t,o,n){n||!k(o)||C(o)||(n=o,o=void 0),this.protocols=o,this.url=t||"Missing URL",this.ssl=/(wss)/i.test(this.url),this.scope=n&&n.scope||e,this.rootScopeFailover=n&&n.rootScopeFailover&&!0,this.useApplyAsync=n&&n.useApplyAsync||!1,this.initialTimeout=n&&n.initialTimeout||500,this.maxTimeout=n&&n.maxTimeout||3e5,this.reconnectIfNotNormalClose=n&&n.reconnectIfNotNormalClose||!1,this.binaryType=n&&n.binaryType||"blob",this._reconnectAttempts=0,this.sendQueue=[],this.onOpenCallbacks=[],this.onMessageCallbacks=[],this.onErrorCallbacks=[],this.onCloseCallbacks=[],f(this._readyStateConstants),t?this._connect():this._setInternalState(0)}return s.prototype._readyStateConstants={CONNECTING:0,OPEN:1,CLOSING:2,CLOSED:3,RECONNECT_ABORTED:4},s.prototype._normalCloseCode=1e3,s.prototype._reconnectableStatusCodes=[4e3],s.prototype.safeDigest=function(e){e&&!this.scope.$$phase&&this.scope.$digest()},s.prototype.bindToScope=function(t){var o=this;return t&&(this.scope=t,this.rootScopeFailover&&this.scope.$on("$destroy",function(){o.scope=e})),o},s.prototype._connect=function(e){!e&&this.socket&&this.socket.readyState===this._readyStateConstants.OPEN||(this.socket=n.create(this.url,this.protocols),this.socket.onmessage=c["default"].bind(this,this._onMessageHandler),this.socket.onopen=c["default"].bind(this,this._onOpenHandler),this.socket.onerror=c["default"].bind(this,this._onErrorHandler),this.socket.onclose=c["default"].bind(this,this._onCloseHandler),this.socket.binaryType=this.binaryType)},s.prototype.fireQueue=function(){for(;this.sendQueue.length&&this.socket.readyState===this._readyStateConstants.OPEN;){var e=this.sendQueue.shift();this.socket.send(d(e.message)||"blob"!=this.binaryType?e.message:JSON.stringify(e.message)),e.deferred.resolve()}},s.prototype.notifyOpenCallbacks=function(e){for(var t=0;t-1)&&this.reconnect()},s.prototype._onErrorHandler=function(e){var t=this;t.useApplyAsync?t.scope.$applyAsync(function(){t.notifyErrorCallbacks(e)}):(t.notifyErrorCallbacks(e),t.safeDigest(!0))},s.prototype._onMessageHandler=function(e){function t(e,t,o){o=m.call(arguments,2),s.useApplyAsync?s.scope.$applyAsync(function(){e.apply(s,o)}):(e.apply(s,o),s.safeDigest(t))}for(var o,n,s=this,r=0;re||e>4)throw new Error("state must be an integer between 0 and 4, got: "+e);h||(this.readyState=e||this.socket.readyState),this._internalConnectionState=e,g(this.sendQueue,function(e){e.deferred.reject("Message cancelled due to closed socket connection")})},h&&h(s.prototype,"readyState",{get:function(){return this._internalConnectionState||this.socket.readyState},set:function(){throw new Error("The readyState property is read-only")}}),function(e,t,o){return new s(e,t,o)}}function i(e){this.create=function(e,t){var o=/wss?:\/\//.exec(e);if(!o)throw new Error("Invalid url provided");return t?new a(e,t):new a(e)},this.createWebSocketBackend=function(t,o){return e.warn("Deprecated: Please use .create(url, protocols)"),this.create(t,o)}}Object.defineProperty(t,"__esModule",{value:!0});var a,c=s(o),l="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol?"symbol":typeof e};if("object"===("undefined"==typeof t?"undefined":l(t))&&"function"==typeof require)try{a=n.Client||n.client||n}catch(u){}a=a||window.WebSocket||window.MozWebSocket;var p=c["default"].noop,f=Object.freeze?Object.freeze:p,h=Object.defineProperty,d=c["default"].isString,y=c["default"].isFunction,b=c["default"].isDefined,k=c["default"].isObject,C=c["default"].isArray,g=c["default"].forEach,m=Array.prototype.slice;Array.prototype.indexOf||(Array.prototype.indexOf=function(e){var t=this.length>>>0,o=Number(arguments[1])||0;for(o=0>o?Math.ceil(o):Math.floor(o),0>o&&(o+=t);t>o;o++)if(o in this&&this[o]===e)return o;return-1}),c["default"].module("ngWebSocket",[]).factory("$websocket",["$rootScope","$q","$timeout","$websocketBackend",r]).factory("WebSocket",["$rootScope","$q","$timeout","WebsocketBackend",r]).service("$websocketBackend",["$log",i]).service("WebSocketBackend",["$log",i]),c["default"].module("angular-websocket",["ngWebSocket"]),t["default"]=c["default"].module("ngWebSocket"),e.exports=t["default"]}); +!function(e,t){if("function"==typeof define&&define.amd)define(["module","exports","angular","ws"],t);else if("undefined"!=typeof exports)t(module,exports,require("angular"),require("ws"));else{var o={exports:{}};t(o,o.exports,e.angular,e.ws),e.angularWebsocket=o.exports}}(this,function(e,t,o,n){"use strict";function s(e){return e&&e.__esModule?e:{default:e}}function r(e,t,o,n){function s(t,o,n){n||!b(o)||k(o)||(n=o,o=void 0),this.protocols=o,this.url=t||"Missing URL",this.ssl=/(wss)/i.test(this.url),this.scope=n&&n.scope||e,this.rootScopeFailover=n&&n.rootScopeFailover&&!0,this.useApplyAsync=n&&n.useApplyAsync||!1,this.initialTimeout=n&&n.initialTimeout||500,this.maxTimeout=n&&n.maxTimeout||3e5,this.reconnectIfNotNormalClose=n&&n.reconnectIfNotNormalClose||!1,this.consoleLogReconnect=!n||void 0===n.consoleLogReconnect||n.consoleLogReconnect,this.binaryType=n&&n.binaryType||"blob",this._reconnectAttempts=0,this.sendQueue=[],this.onOpenCallbacks=[],this.onMessageCallbacks=[],this.onErrorCallbacks=[],this.onCloseCallbacks=[],p(this._readyStateConstants),t?this._connect():this._setInternalState(0)}return s.prototype._readyStateConstants={CONNECTING:0,OPEN:1,CLOSING:2,CLOSED:3,RECONNECT_ABORTED:4},s.prototype._normalCloseCode=1e3,s.prototype._reconnectableStatusCodes=[4e3],s.prototype.safeDigest=function(e){e&&!this.scope.$$phase&&this.scope.$digest()},s.prototype.bindToScope=function(t){var o=this;return t&&(this.scope=t,this.rootScopeFailover&&this.scope.$on("$destroy",function(){o.scope=e})),o},s.prototype._connect=function(e){!e&&this.socket&&this.socket.readyState===this._readyStateConstants.OPEN||(this.socket=n.create(this.url,this.protocols),this.socket.onmessage=c.default.bind(this,this._onMessageHandler),this.socket.onopen=c.default.bind(this,this._onOpenHandler),this.socket.onerror=c.default.bind(this,this._onErrorHandler),this.socket.onclose=c.default.bind(this,this._onCloseHandler),this.socket.binaryType=this.binaryType)},s.prototype.fireQueue=function(){for(;this.sendQueue.length&&this.socket.readyState===this._readyStateConstants.OPEN;){var e=this.sendQueue.shift();this.socket.send(h(e.message)||"blob"!=this.binaryType?e.message:JSON.stringify(e.message)),e.deferred.resolve()}},s.prototype.notifyOpenCallbacks=function(e){for(var t=0;t-1)&&this.reconnect(e),t.useApplyAsync?t.scope.$applyAsync(function(){t.notifyCloseCallbacks(e)}):(t.notifyCloseCallbacks(e),t.safeDigest(!0))},s.prototype._onErrorHandler=function(e){var t=this;t.useApplyAsync?t.scope.$applyAsync(function(){t.notifyErrorCallbacks(e)}):(t.notifyErrorCallbacks(e),t.safeDigest(!0))},s.prototype._onMessageHandler=function(e){function t(e,t,o){o=g.call(arguments,2),s.useApplyAsync?s.scope.$applyAsync(function(){e.apply(s,o)}):(e.apply(s,o),s.safeDigest(t))}for(var o,n,s=this,r=0;r4)throw new Error("state must be an integer between 0 and 4, got: "+e);f||(this.readyState=e||this.socket.readyState),this._internalConnectionState=e,C(this.sendQueue,function(e){e.deferred.reject("Message cancelled due to closed socket connection")})},f&&f(s.prototype,"readyState",{get:function(){return this._internalConnectionState||this.socket.readyState},set:function(){throw new Error("The readyState property is read-only")}}),function(e,t,o){return new s(e,t,o)}}function i(e){this.create=function(e,t){var o=/wss?:\/\//.exec(e);if(!o)throw new Error("Invalid url provided");return t?new a(e,t):new a(e)},this.createWebSocketBackend=function(t,o){return e.warn("Deprecated: Please use .create(url, protocols)"),this.create(t,o)}}Object.defineProperty(t,"__esModule",{value:!0});var a,c=s(o),l="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol?"symbol":typeof e};if("undefined"==typeof window)try{a=n.Client||n.client||n}catch(e){}a=a||window.WebSocket||window.MozWebSocket;var u=c.default.noop,p=Object.freeze?Object.freeze:u,f=Object.defineProperty,h=c.default.isString,d=c.default.isFunction,y=c.default.isDefined,b=c.default.isObject,k=c.default.isArray,C=c.default.forEach,g=Array.prototype.slice;Array.prototype.indexOf||(Array.prototype.indexOf=function(e){var t=this.length>>>0,o=Number(arguments[1])||0;for(o=o<0?Math.ceil(o):Math.floor(o),o<0&&(o+=t);o -1) { + this.reconnect(event); + } if (self.useApplyAsync) { self.scope.$applyAsync(function() { self.notifyCloseCallbacks(event); @@ -208,9 +212,6 @@ function $WebSocketProvider($rootScope, $q, $timeout, $websocketBackend) { self.notifyCloseCallbacks(event); self.safeDigest(true); } - if ((this.reconnectIfNotNormalClose && event.code !== this._normalCloseCode) || this._reconnectableStatusCodes.indexOf(event.code) > -1) { - this.reconnect(); - } }; $WebSocket.prototype._onErrorHandler = function _onErrorHandler(event) { @@ -307,13 +308,18 @@ function $WebSocketProvider($rootScope, $q, $timeout, $websocketBackend) { return promise; }; - $WebSocket.prototype.reconnect = function reconnect() { + $WebSocket.prototype.reconnect = function reconnect(event) { this.close(); var backoffDelay = this._getBackoffDelay(++this._reconnectAttempts); var backoffDelaySeconds = backoffDelay / 1000; - console.log('Reconnecting in ' + backoffDelaySeconds + ' seconds'); + if (typeof event === 'object') { + event.reconnectDelaySeconds = backoffDelaySeconds; + } + if (this.consoleLogReconnect) { + console.log('Reconnecting in ' + backoffDelaySeconds + ' seconds'); + } $timeout(angular.bind(this, this._connect), backoffDelay); diff --git a/test/angular-websocket.spec.js b/test/angular-websocket.spec.js index a5e4f4e..732b3fe 100644 --- a/test/angular-websocket.spec.js +++ b/test/angular-websocket.spec.js @@ -235,6 +235,30 @@ describe('angular-websocket', function() { $websocketBackend.flush(); })); + + it('should log if consoleLogReconnect is not set', function() { + console.log = jasmine.createSpy('log') + var url = 'ws://foo/onclose'; + $websocketBackend.expectConnect(url); + + var ws = $websocket(url); + ws.reconnect(); + expect(console.log).toHaveBeenCalled(); + + $websocketBackend.flush(); + }); + + it('should not log if consoleLogReconnect is false', function() { + console.log = jasmine.createSpy('log') + var url = 'ws://foo/onclose'; + $websocketBackend.expectConnect(url); + + var ws = $websocket(url, {consoleLogReconnect: false}); + ws.reconnect(); + expect(console.log).not.toHaveBeenCalled(); + + $websocketBackend.flush(); + }); }); @@ -371,6 +395,21 @@ describe('angular-websocket', function() { $websocketBackend.flush(); }); + it('should add reconnectDelaySeconds to close event', function() { + var url = 'ws://foo/onclose'; + $websocketBackend.expectConnect(url); + + var ws = $websocket(url, {reconnectIfNotNormalClose: true}); + var onCloseSpy = jasmine.createSpy('onClose'); + ws.onClose(onCloseSpy); + ws._onCloseHandler({code: 4000}); + expect(onCloseSpy).toHaveBeenCalled(); + var closeEvent = onCloseSpy.calls.mostRecent().args[0]; + expect(closeEvent.reconnectDelaySeconds).toEqual(jasmine.any(Number)) + + $websocketBackend.flush(); + }); + it('should not call .reconnect if the CloseEvent indicates an intentional close and the reconnectIfNotNormalClose flag is false', function() { var url = 'ws://foo/onclose'; $websocketBackend.expectConnect(url);