Skip to content
This repository has been archived by the owner on Apr 2, 2024. It is now read-only.

Commit

Permalink
feat: Add getter for determining if WebSocket is connected (#656)
Browse files Browse the repository at this point in the history
  • Loading branch information
hjoelr committed Jan 3, 2022
1 parent 8e1bdb8 commit 7947d7f
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 0 deletions.
38 changes: 38 additions & 0 deletions src/client/WebSocketClient.test.ts
Expand Up @@ -84,6 +84,44 @@ describe('WebSocketClient', () => {
});
});

describe('connected', () => {
it('returns false when called before the connection is created', done => {
const ws = createWebSocketClient();
expect(ws.connected).toBe(false);
done();
});
it('returns true when called after the connection is created', done => {
const ws = createWebSocketClient();

ws.on(WebSocketEvent.ON_CLOSE, () => {
done();
});

ws.on(WebSocketEvent.ON_OPEN, () => {
expect(ws.connected).toBe(true);

ws.disconnect();
});

ws.connect();
});

it('returns false when called after the connection is closed', done => {
const ws = createWebSocketClient();

ws.on(WebSocketEvent.ON_CLOSE, () => {
expect(ws.connected).toBe(false);
done();
});

ws.on(WebSocketEvent.ON_OPEN, () => {
ws.disconnect();
});

ws.connect();
});
});

describe('constructor', () => {
it('it signals an event when the WebSocket connection is established', done => {
const ws = createWebSocketClient();
Expand Down
9 changes: 9 additions & 0 deletions src/client/WebSocketClient.ts
Expand Up @@ -471,6 +471,15 @@ export class WebSocketClient extends EventEmitter {
}
}

/**
* A simple function to determine if the websocket appears to be open.
*
* @returns True if the websocket has been opened and has not closed.
*/
get connected(): boolean {
return undefined !== this.socket;
}

async sendMessage(message: WebSocketRequest): Promise<void> {
if (!this.socket) {
throw new Error(`Failed to send message of type "${message.type}": You need to connect to the WebSocket first.`);
Expand Down

0 comments on commit 7947d7f

Please sign in to comment.