Skip to content

Commit 62eddf9

Browse files
authored
Refrehs token asap (#88)
1 parent b19e47c commit 62eddf9

File tree

1 file changed

+16
-1
lines changed

1 file changed

+16
-1
lines changed

lib/socket.ts

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,19 @@ export function createSocket(options: ConnectionOptions): Promise<WebSocket> {
2121
}
2222
const auth = options.auth;
2323

24+
// Start refreshing expired tokens even before the WS connection is open.
25+
// We know that we will need auth anyway.
26+
let authRefreshTask = auth.expired
27+
? auth.refreshAccessToken().then(
28+
() => {
29+
authRefreshTask = undefined;
30+
},
31+
() => {
32+
authRefreshTask = undefined;
33+
}
34+
)
35+
: undefined;
36+
2437
// Convert from http:// -> ws://, https:// -> wss://
2538
const url = auth.wsUrl;
2639

@@ -73,7 +86,9 @@ export function createSocket(options: ConnectionOptions): Promise<WebSocket> {
7386
// Auth is mandatory, so we can send the auth message right away.
7487
const handleOpen = async (event: MessageEventInit) => {
7588
try {
76-
if (auth.expired) await auth.refreshAccessToken();
89+
if (auth.expired) {
90+
await (authRefreshTask ? authRefreshTask : auth.refreshAccessToken());
91+
}
7792
socket.send(JSON.stringify(messages.auth(auth.accessToken)));
7893
} catch (err) {
7994
// Refresh token failed

0 commit comments

Comments
 (0)