Skip to content

Commit

Permalink
Add reconnect event to ReconnectingWebsocket
Browse files Browse the repository at this point in the history
Closes #101.
  • Loading branch information
chadxz committed Oct 31, 2018
1 parent 315ef7f commit 12a98fd
Showing 1 changed file with 16 additions and 0 deletions.
16 changes: 16 additions & 0 deletions src/events/ReconnectingWebSocket.js
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,9 @@ export default class ReconnectingWebSocket extends events.EventEmitter {
/** @private */
this._reconnect = reconnect;

/** @private */
this._reconnecting = false;

debug("attempting initial connection", { url });
this.connect(err => {
if (err) {
Expand All @@ -91,6 +94,7 @@ export default class ReconnectingWebSocket extends events.EventEmitter {
*/
connect(callback) {
const operation = retry.operation(this._retryOptions);
const timeouts = retry.timeouts(this._retryOptions);

operation.attempt(attemptNumber => {
const numRetries = attemptNumber - 1;
Expand All @@ -101,6 +105,13 @@ export default class ReconnectingWebSocket extends events.EventEmitter {
this._ws.close();
}

if (this._reconnecting) {
this.emit("reconnecting", {
attempts: attemptNumber,
nextTimeout: timeouts[attemptNumber]
});
}

/** @private */
this._ws = new WebSocket(this._url, this._wsOptions);

Expand All @@ -112,6 +123,7 @@ export default class ReconnectingWebSocket extends events.EventEmitter {
return;
}

this._reconnecting = true;
if (operation.retry(err)) {
return;
}
Expand All @@ -120,11 +132,13 @@ export default class ReconnectingWebSocket extends events.EventEmitter {
debug('connection attempts exhaused',
{ err, reconnect: this._reconnect, numRetries });

this._reconnecting = false;
callback(operation.mainError());
};

this._ws.once("error", handleConnectError);
this._ws.once("open", () => {
this._reconnecting = false;
debug("connected", { numRetries });
this._ws.removeListener("error", handleConnectError);
this._ws.on("message", this.emit.bind(this, "message"));
Expand Down Expand Up @@ -154,6 +168,7 @@ export default class ReconnectingWebSocket extends events.EventEmitter {
this.emit("disconnected", { reason: "error", err });
debug("attempting to reconnect");

this._reconnecting = true;
this.connect(err => {
if (err) {
this.emit("error", err);
Expand Down Expand Up @@ -182,6 +197,7 @@ export default class ReconnectingWebSocket extends events.EventEmitter {
this.emit("disconnected", { reason: "close", code, message });
debug("attempting to reconnect");

this._reconnecting = true;
this.connect(err => {
if (err) {
this.emit("error", err);
Expand Down

0 comments on commit 12a98fd

Please sign in to comment.