@@ -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
*
@@ -359,6 +371,7 @@ class Client {
359
371
private realtime: Realtime = {
360
372
socket: undefined,
361
373
timeout: undefined,
374
+ heartbeat: undefined,
362
375
url: '',
363
376
channels: new Set(),
364
377
subscriptions: new Map(),
@@ -384,6 +397,17 @@ class Client {
384
397
return 60_000;
385
398
}
386
399
},
400
+ createHeartbeat: () => {
401
+ if (this.realtime.heartbeat) {
402
+ clearTimeout(this.realtime.heartbeat);
403
+ }
404
+
405
+ this.realtime.heartbeat = window?.setInterval(() => {
406
+ this.realtime.socket?.send(JSON.stringify({
407
+ type: 'ping'
408
+ }));
409
+ }, 20_000);
410
+ },
387
411
createSocket: () => {
388
412
if (this.realtime.channels.size < 1) {
389
413
this.realtime.reconnect = false;
@@ -417,6 +441,7 @@ class Client {
417
441
this.realtime.socket.addEventListener('message', this.realtime.onMessage);
418
442
this.realtime.socket.addEventListener('open', _event => {
419
443
this.realtime.reconnectAttempts = 0;
444
+ this.realtime.createHeartbeat();
420
445
});
421
446
this.realtime.socket.addEventListener('close', event => {
422
447
if (
0 commit comments