@@ -2,16 +2,12 @@ import { RealtimeChannel, RealtimeClient, Transformers } from '@supabase/realtim
2
2
import { SupabaseRealtimePayload } from './types'
3
3
4
4
export class SupabaseRealtimeClient {
5
+ socket : RealtimeClient
5
6
channel : RealtimeChannel
6
7
7
- constructor ( socket : RealtimeClient , name : string , token : string , opts ?: { [ key : string ] : any } ) {
8
- let chanParams : Record < string , string > = { user_token : token }
9
-
10
- if ( opts ) {
11
- chanParams = { ...chanParams , ...opts }
12
- }
13
-
14
- this . channel = socket . channel ( `realtime:${ name } ` , chanParams ) as RealtimeChannel
8
+ constructor ( socket : RealtimeClient , name : string , opts : { [ key : string ] : any } = { } ) {
9
+ this . socket = socket
10
+ this . channel = socket . channel ( `realtime:${ name } ` , opts ) as RealtimeChannel
15
11
}
16
12
17
13
private getPayloadRecords ( payload : any ) {
@@ -66,13 +62,30 @@ export class SupabaseRealtimeClient {
66
62
* Enables the channel.
67
63
*/
68
64
subscribe ( callback : Function = ( ) => { } ) {
65
+ // if the socket already has a good accessToken
66
+ // we can just use it straight away
67
+ if ( this . socket . accessToken ) {
68
+ this . channel . updateJoinPayload ( {
69
+ user_token : this . socket . accessToken ,
70
+ } )
71
+ }
72
+
69
73
this . channel . onError ( ( e : Error ) => callback ( 'CHANNEL_ERROR' , e ) )
70
74
this . channel . onClose ( ( ) => callback ( 'CLOSED' ) )
71
75
this . channel
72
76
. subscribe ( )
73
- . receive ( 'ok' , ( ) => callback ( 'SUBSCRIBED' ) )
77
+ . receive ( 'ok' , ( ) => {
78
+ callback ( 'SUBSCRIBED' )
79
+
80
+ // re-set the accessToken again in case it was set while
81
+ // the subscription was isJoining
82
+ if ( this . socket . accessToken ) {
83
+ this . socket . setAuth ( this . socket . accessToken )
84
+ }
85
+ } )
74
86
. receive ( 'error' , ( e : Error ) => callback ( 'CHANNEL_ERROR' , e ) )
75
87
. receive ( 'timeout' , ( ) => callback ( 'RETRYING_AFTER_TIMEOUT' ) )
88
+
76
89
return this . channel
77
90
}
78
91
}
0 commit comments