Skip to content

Commit 06fb4f2

Browse files
Add event parameters, incorporate api_key parameter
Add an optional event parameter to the onClose and onOpen callbacks Incorporates the api_key as a searchParam in the websocket URL
1 parent fc8da45 commit 06fb4f2

File tree

2 files changed

+15
-11
lines changed

2 files changed

+15
-11
lines changed

src/utils/url/websocket.ts

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -4,18 +4,19 @@ import { Api } from "../../api";
44

55
/**
66
*
7-
* @param basePath The {@link Api.basePath} to connect to
7+
* @param param0 The authenticated {@link Api} instance
88
*/
9-
export default function getWebSocketUrl(basePath: string) : URL {
9+
export default function getWebSocketUrl({ accessToken, basePath } : Api) : URL {
1010

1111
let protocol;
1212

1313
const baseUrl = parseUrl(basePath)
1414

15-
if (baseUrl.protocol.startsWith(HTTP_PROTOCOL))
16-
protocol = WS_PROTOCOL
17-
else
18-
protocol = WSS_PROTOCOL
15+
if (baseUrl.protocol.startsWith(HTTP_PROTOCOL)) protocol = WS_PROTOCOL
16+
else protocol = WSS_PROTOCOL
1917

20-
return new URL(`${protocol}//${baseUrl.host}`)
18+
let url = new URL(`${protocol}//${baseUrl.host}/socket`)
19+
url.searchParams.append("api_key", accessToken)
20+
21+
return url
2122
}

src/websocket/websocket-service.ts

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -28,17 +28,20 @@ export class WebSocketService {
2828
* Ensures a websocket connection to the server is active by establishing a new connection
2929
* if a connection doesn't already exist or the previous connection is closed.
3030
*
31-
* Depends on the {@link Api.basePath} and {@link Api.accessToken} being valid and
31+
* Depends on the {@link Api.accessToken} being valid and
3232
* populated.
3333
*
3434
* @param onOpen An optional callback to run when the socket is opened
3535
* @param onClose An optional callback to run when the socket is closed
3636
*/
37-
ensureWebSocket(onOpen?: () => Promise<void>, onClose?: () => Promise<void>) {
37+
ensureWebSocket(
38+
onOpen?: (e?: Event) => Promise<void>,
39+
onClose?: (e?: CloseEvent) => Promise<void>
40+
) {
3841

3942
if (this.shouldOpenWebSocket(this.api.accessToken)) {
4043

41-
const webSocketUrl = getWebSocketUrl(this.api.basePath)
44+
const webSocketUrl = getWebSocketUrl(this.api)
4245

4346
this.socket = new WebSocket(webSocketUrl)
4447
}
@@ -48,6 +51,6 @@ export class WebSocketService {
4851
}
4952

5053
sendMessage(message: SessionsMessage) {
51-
54+
this.socket.send(JSON.stringify(message))
5255
}
5356
}

0 commit comments

Comments
 (0)