Skip to content

Commit 27d8ecd

Browse files
Merge pull request #1010 from appwrite/feat-implement-heartbeat
feat: implement heartbeat
2 parents 675362c + ae553cc commit 27d8ecd

File tree

1 file changed

+29
-4
lines changed

1 file changed

+29
-4
lines changed

templates/web/src/client.ts.twig

Lines changed: 29 additions & 4 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
*
@@ -359,6 +371,7 @@ class Client {
359371
private realtime: Realtime = {
360372
socket: undefined,
361373
timeout: undefined,
374+
heartbeat: undefined,
362375
url: '',
363376
channels: new Set(),
364377
subscriptions: new Map(),
@@ -384,6 +397,17 @@ class Client {
384397
return 60_000;
385398
}
386399
},
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+
},
387411
createSocket: () => {
388412
if (this.realtime.channels.size < 1) {
389413
this.realtime.reconnect = false;
@@ -417,6 +441,7 @@ class Client {
417441
this.realtime.socket.addEventListener('message', this.realtime.onMessage);
418442
this.realtime.socket.addEventListener('open', _event => {
419443
this.realtime.reconnectAttempts = 0;
444+
this.realtime.createHeartbeat();
420445
});
421446
this.realtime.socket.addEventListener('close', event => {
422447
if (

0 commit comments

Comments
 (0)