@@ -19,9 +19,9 @@ type Headers = {
19
19
*/
20
20
type RealtimeResponse = {
21
21
/**
22
- * Type of the response: 'error', 'event', 'connected', or 'response'.
22
+ * Type of the response: 'error', 'event', 'connected', 'pong', or 'response'.
23
23
*/
24
- type : 'error' | 'event' | 'connected' | 'response' ;
24
+ type : 'error' | 'event' | 'connected' | 'response' | 'pong' ;
25
25
26
26
/**
27
27
* Data associated with the response based on the response type.
@@ -129,6 +129,8 @@ type RealtimeRequestAuthenticate = {
129
129
session : string ;
130
130
}
131
131
132
+ type TimeoutHandle = ReturnType < typeof setTimeout > | number ;
133
+
132
134
/**
133
135
* Realtime interface representing the structure of a realtime communication object.
134
136
*/
@@ -139,9 +141,14 @@ type Realtime = {
139
141
socket ?: WebSocket ;
140
142
141
143
/**
142
- * Timeout duration for communication operations.
144
+ * Timeout for reconnect operations.
143
145
*/
144
- timeout ?: number ;
146
+ timeout ?: TimeoutHandle ;
147
+
148
+ /**
149
+ * Heartbeat interval for the realtime connection.
150
+ */
151
+ heartbeat ?: TimeoutHandle ;
145
152
146
153
/**
147
154
* URL for establishing the WebSocket connection.
@@ -196,6 +203,11 @@ type Realtime = {
196
203
*/
197
204
createSocket : ( ) => void ;
198
205
206
+ /**
207
+ * Function to create a new heartbeat interval.
208
+ */
209
+ createHeartbeat : ( ) => void ;
210
+
199
211
/**
200
212
* Function to clean up resources associated with specified channels.
201
213
*
@@ -394,6 +406,7 @@ class Client {
394
406
private realtime : Realtime = {
395
407
socket : undefined ,
396
408
timeout : undefined ,
409
+ heartbeat : undefined ,
397
410
url : '' ,
398
411
channels : new Set ( ) ,
399
412
subscriptions : new Map ( ) ,
@@ -419,6 +432,17 @@ class Client {
419
432
return 60_000 ;
420
433
}
421
434
} ,
435
+ createHeartbeat : ( ) => {
436
+ if ( this . realtime . heartbeat ) {
437
+ clearTimeout ( this . realtime . heartbeat ) ;
438
+ }
439
+
440
+ this . realtime . heartbeat = window ?. setInterval ( ( ) => {
441
+ this . realtime . socket ?. send ( JSON . stringify ( {
442
+ type : 'ping'
443
+ } ) ) ;
444
+ } , 20_000 ) ;
445
+ } ,
422
446
createSocket : ( ) => {
423
447
if ( this . realtime . channels . size < 1 ) {
424
448
this . realtime . reconnect = false ;
@@ -452,6 +476,7 @@ class Client {
452
476
this . realtime . socket . addEventListener ( 'message' , this . realtime . onMessage ) ;
453
477
this . realtime . socket . addEventListener ( 'open' , _event => {
454
478
this . realtime . reconnectAttempts = 0 ;
479
+ this . realtime . createHeartbeat ( ) ;
455
480
} ) ;
456
481
this . realtime . socket . addEventListener ( 'close' , event => {
457
482
if (
@@ -721,7 +746,6 @@ class Client {
721
746
}
722
747
}
723
748
724
-
725
749
return output ;
726
750
}
727
751
}
0 commit comments