Skip to content
This repository has been archived by the owner on Dec 13, 2020. It is now read-only.

Commit

Permalink
Merge pull request #1290 from metasfresh/dev-1258
Browse files Browse the repository at this point in the history
Handle socket reconnections asynchronously and gracefully
  • Loading branch information
teosarca authored Oct 20, 2017
2 parents a75d6cc + 37f7887 commit 19f3cb3
Showing 1 changed file with 31 additions and 14 deletions.
45 changes: 31 additions & 14 deletions src/actions/WindowActions.js
Original file line number Diff line number Diff line change
Expand Up @@ -982,20 +982,37 @@ export function collapsedMap(
}

export function connectWS(topic, cb) {
(this.sockClient && this.sockClient.connected) &&
this.sockClient.disconnect();

this.sock = new SockJs(config.WS_URL);
this.sockClient = Stomp.Stomp.over(this.sock);
this.sockClient.debug = null;
this.sockClient.connect({}, () => {
this.sockClient.subscribe(topic, msg => {
cb(JSON.parse(msg.body));
});
});
const subscribe = ({ tries = 3 } = {}) => {
if (this.sockClient.connected || tries <= 0) {
this.sockSubscription = this.sockClient.subscribe(topic, (msg) => {
cb(JSON.parse(msg.body));
});
} else {
// not ready yet
setTimeout(() => { subscribe({ tries: tries - 1 }); }, 200);
}
};
const connect = () => {
this.sock = new SockJs(config.WS_URL);
this.sockClient = Stomp.Stomp.over(this.sock);
this.sockClient.debug = null;
this.sockClient.connect({}, subscribe);
}
const connected = disconnectWS.call(this, connect);

if (!connected) {
connect();
}
}

export function disconnectWS() {
(this.sockClient && this.sockClient.connected) &&
this.sockClient.disconnect();
export function disconnectWS(callback) {
const connected = this.sockClient && this.sockClient.connected &&
this.sockSubscription;

if (connected) {
this.sockSubscription.unsubscribe();
this.sockClient.disconnect(callback);
}

return connected;
}

0 comments on commit 19f3cb3

Please sign in to comment.