Skip to content

Commit 9b06da9

Browse files
committed
chore: release
1 parent e902ef2 commit 9b06da9

File tree

1 file changed

+29
-5
lines changed

1 file changed

+29
-5
lines changed

src/client.ts

Lines changed: 29 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -19,9 +19,9 @@ type Headers = {
1919
*/
2020
type RealtimeResponse = {
2121
/**
22-
* Type of the response: 'error', 'event', 'connected', or 'response'.
22+
* Type of the response: 'error', 'event', 'connected', 'pong', or 'response'.
2323
*/
24-
type: 'error' | 'event' | 'connected' | 'response';
24+
type: 'error' | 'event' | 'connected' | 'response' | 'pong';
2525

2626
/**
2727
* Data associated with the response based on the response type.
@@ -129,6 +129,8 @@ type RealtimeRequestAuthenticate = {
129129
session: string;
130130
}
131131

132+
type TimeoutHandle = ReturnType<typeof setTimeout> | number;
133+
132134
/**
133135
* Realtime interface representing the structure of a realtime communication object.
134136
*/
@@ -139,9 +141,14 @@ type Realtime = {
139141
socket?: WebSocket;
140142

141143
/**
142-
* Timeout duration for communication operations.
144+
* Timeout for reconnect operations.
143145
*/
144-
timeout?: number;
146+
timeout?: TimeoutHandle;
147+
148+
/**
149+
* Heartbeat interval for the realtime connection.
150+
*/
151+
heartbeat?: TimeoutHandle;
145152

146153
/**
147154
* URL for establishing the WebSocket connection.
@@ -196,6 +203,11 @@ type Realtime = {
196203
*/
197204
createSocket: () => void;
198205

206+
/**
207+
* Function to create a new heartbeat interval.
208+
*/
209+
createHeartbeat: () => void;
210+
199211
/**
200212
* Function to clean up resources associated with specified channels.
201213
*
@@ -394,6 +406,7 @@ class Client {
394406
private realtime: Realtime = {
395407
socket: undefined,
396408
timeout: undefined,
409+
heartbeat: undefined,
397410
url: '',
398411
channels: new Set(),
399412
subscriptions: new Map(),
@@ -419,6 +432,17 @@ class Client {
419432
return 60_000;
420433
}
421434
},
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+
},
422446
createSocket: () => {
423447
if (this.realtime.channels.size < 1) {
424448
this.realtime.reconnect = false;
@@ -452,6 +476,7 @@ class Client {
452476
this.realtime.socket.addEventListener('message', this.realtime.onMessage);
453477
this.realtime.socket.addEventListener('open', _event => {
454478
this.realtime.reconnectAttempts = 0;
479+
this.realtime.createHeartbeat();
455480
});
456481
this.realtime.socket.addEventListener('close', event => {
457482
if (
@@ -721,7 +746,6 @@ class Client {
721746
}
722747
}
723748

724-
725749
return output;
726750
}
727751
}

0 commit comments

Comments
 (0)