Skip to content

Commit efbf5b5

Browse files
filipecabacogrdsdev
authored andcommitted
fix: setAuth ran automatically for realtime; prioritize setAuth tasks
# Conflicts: # test/unit/SupabaseClient.test.ts
1 parent 4505a9b commit efbf5b5

File tree

2 files changed

+334
-108
lines changed

2 files changed

+334
-108
lines changed

src/SupabaseClient.ts

Lines changed: 20 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -138,7 +138,7 @@ export default class SupabaseClient<
138138
})
139139

140140
if (!settings.accessToken) {
141-
this._listenForAuthEvents()
141+
setTimeout(() => this._listenForAuthEvents(), 0)
142142
}
143143
}
144144

@@ -278,7 +278,7 @@ export default class SupabaseClient<
278278
return this.realtime.removeAllChannels()
279279
}
280280

281-
private async _getAccessToken() {
281+
protected async _getAccessToken() {
282282
if (this.accessToken) {
283283
return await this.accessToken()
284284
}
@@ -288,7 +288,7 @@ export default class SupabaseClient<
288288
return data.session?.access_token ?? null
289289
}
290290

291-
private _initSupabaseAuthClient(
291+
protected _initSupabaseAuthClient(
292292
{
293293
autoRefreshToken,
294294
persistSession,
@@ -324,21 +324,23 @@ export default class SupabaseClient<
324324
})
325325
}
326326

327-
private _initRealtimeClient(options: RealtimeClientOptions) {
327+
protected _initRealtimeClient(options: RealtimeClientOptions) {
328328
return new RealtimeClient(this.realtimeUrl.href, {
329329
...options,
330330
params: { ...{ apikey: this.supabaseKey }, ...options?.params },
331331
})
332332
}
333333

334-
private _listenForAuthEvents() {
335-
let data = this.auth.onAuthStateChange((event, session) => {
336-
this._handleTokenChanged(event, 'CLIENT', session?.access_token)
334+
protected async _listenForAuthEvents() {
335+
return await this.auth.onAuthStateChange((event, session) => {
336+
setTimeout(
337+
async () => await this._handleTokenChanged(event, 'CLIENT', session?.access_token),
338+
0
339+
)
337340
})
338-
return data
339341
}
340342

341-
private _handleTokenChanged(
343+
protected async _handleTokenChanged(
342344
event: AuthChangeEvent,
343345
source: 'CLIENT' | 'STORAGE',
344346
token?: string
@@ -348,10 +350,16 @@ export default class SupabaseClient<
348350
this.changedAccessToken !== token
349351
) {
350352
this.changedAccessToken = token
353+
this.realtime.setAuth(token)
351354
} else if (event === 'SIGNED_OUT') {
352-
this.realtime.setAuth()
353-
if (source == 'STORAGE') this.auth.signOut()
354-
this.changedAccessToken = undefined
355+
try {
356+
await this.realtime.setAuth()
357+
if (source == 'STORAGE') this.auth.signOut()
358+
} catch (error) {
359+
console.log('Failed to set auth for realtime client:', error)
360+
} finally {
361+
this.changedAccessToken = undefined
362+
}
355363
}
356364
}
357365
}

0 commit comments

Comments
 (0)