|
1 |
| -import { RealtimeSubscription, RealtimeClient, Transformers } from '@supabase/realtime-js' |
2 |
| -import { GenericObject, SupabaseEventTypes, SupabaseRealtimePayload } from './types' |
| 1 | +import { RealtimeClient, RealtimeSubscription, Transformers } from '@supabase/realtime-js' |
| 2 | +import { SupabaseEventTypes, SupabaseRealtimePayload } from './types' |
3 | 3 |
|
4 | 4 | export class SupabaseRealtimeClient {
|
| 5 | + socket: RealtimeClient |
5 | 6 | subscription: RealtimeSubscription
|
6 | 7 |
|
7 |
| - constructor(socket: RealtimeClient, headers: GenericObject, schema: string, tableName: string) { |
8 |
| - const chanParams: GenericObject = {} |
| 8 | + constructor(socket: RealtimeClient, schema: string, tableName: string) { |
9 | 9 | const topic = tableName === '*' ? `realtime:${schema}` : `realtime:${schema}:${tableName}`
|
10 |
| - const userToken = headers['Authorization'].split(' ')[1] |
11 | 10 |
|
12 |
| - if (userToken) { |
13 |
| - chanParams['user_token'] = userToken |
14 |
| - } |
15 |
| - |
16 |
| - this.subscription = socket.channel(topic, chanParams) as RealtimeSubscription |
| 11 | + this.socket = socket |
| 12 | + this.subscription = socket.channel(topic) as RealtimeSubscription |
17 | 13 | }
|
18 | 14 |
|
19 | 15 | private getPayloadRecords(payload: any) {
|
@@ -62,13 +58,30 @@ export class SupabaseRealtimeClient {
|
62 | 58 | * Enables the subscription.
|
63 | 59 | */
|
64 | 60 | subscribe(callback: Function = () => {}) {
|
| 61 | + // if the socket already has a good accessToken |
| 62 | + // we can just use it strait away∏ |
| 63 | + if (this.socket.accessToken) { |
| 64 | + this.subscription.updateJoinPayload({ |
| 65 | + user_token: this.socket.accessToken, |
| 66 | + }) |
| 67 | + } |
| 68 | + |
65 | 69 | this.subscription.onError((e: Error) => callback('SUBSCRIPTION_ERROR', e))
|
66 | 70 | this.subscription.onClose(() => callback('CLOSED'))
|
67 | 71 | this.subscription
|
68 | 72 | .subscribe()
|
69 |
| - .receive('ok', () => callback('SUBSCRIBED')) |
| 73 | + .receive('ok', () => { |
| 74 | + callback('SUBSCRIBED') |
| 75 | + |
| 76 | + // re-set the accessToken again in case it was set while |
| 77 | + // the subscription was isJoining |
| 78 | + if (this.socket.accessToken) { |
| 79 | + this.socket.setAuth(this.socket.accessToken) |
| 80 | + } |
| 81 | + }) |
70 | 82 | .receive('error', (e: Error) => callback('SUBSCRIPTION_ERROR', e))
|
71 | 83 | .receive('timeout', () => callback('RETRYING_AFTER_TIMEOUT'))
|
| 84 | + |
72 | 85 | return this.subscription
|
73 | 86 | }
|
74 | 87 | }
|
0 commit comments