Skip to content

Commit

Permalink
connection: Make disconnect return if socket is absent
Browse files Browse the repository at this point in the history
Although stop() should be used instead

Fixes #1013
  • Loading branch information
sonnyp committed Jan 6, 2025
1 parent b612ec6 commit b25e478
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 3 deletions.
6 changes: 4 additions & 2 deletions packages/connection/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -179,6 +179,7 @@ class Connection extends EventEmitter {
}

_status(status, ...args) {
if (this.status === status) return;
this.status = status;
this.emit("status", status, ...args);
this.emit(status, ...args);
Expand Down Expand Up @@ -242,8 +243,9 @@ class Connection extends EventEmitter {
* https://tools.ietf.org/html/rfc7395#section-3.6
*/
async disconnect(timeout = this.timeout) {
if (this.socket) this._status("disconnecting");
if (!this.socket) return;

this._status("disconnecting");
this.socket.end();

// The 'disconnect' status is set by the socket 'close' listener
Expand Down Expand Up @@ -281,7 +283,7 @@ class Connection extends EventEmitter {
async stop() {
const el = await this._end();
this.jid = null;
if (this.status !== "offline") this._status("offline", el);
this._status("offline", el);
return el;
}

Expand Down
7 changes: 7 additions & 0 deletions packages/connection/test/disconnect.js
Original file line number Diff line number Diff line change
Expand Up @@ -46,3 +46,10 @@ test("rejects if socket.end throws", (done) => {
done();
});
});

test("resolves if socket is absent", async () => {
const conn = new Connection();
conn.socket = null;

await expect(conn.disconnect()).toResolve();
});
7 changes: 6 additions & 1 deletion packages/websocket/lib/Socket.js
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,12 @@ export default class Socket extends EventEmitter {
if (WebSocket === WS) {
this.socket.send(data, fn);
} else {
this.socket.send(data);
try {
this.socket.send(data);
} catch (err) {
fn(err);
return;
}
fn();
}
}
Expand Down

0 comments on commit b25e478

Please sign in to comment.