Skip to content

Commit

Permalink
feat: realtime heartbeat
Browse files Browse the repository at this point in the history
  • Loading branch information
loks0n committed Dec 30, 2024
1 parent 9cc1393 commit bd5bb16
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 2 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
"name": "react-native-appwrite",
"homepage": "https://appwrite.io/support",
"description": "Appwrite is an open-source self-hosted backend server that abstract and simplify complex and repetitive development tasks behind a very simple REST API",
"version": "0.5.0",
"version": "0.6.0",
"license": "BSD-3-Clause",
"main": "dist/cjs/sdk.js",
"exports": {
Expand Down
26 changes: 25 additions & 1 deletion src/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,17 @@ type RealtimeRequestAuthenticate = {

type Realtime = {
socket?: WebSocket;

/**
* Timeout for reconnect operations.
*/
timeout?: number;

/**
* Heartbeat interval for the realtime connection.
*/
heartbeat?: number;

url?: string;
lastMessage?: RealtimeResponse;
channels: Set<string>;
Expand All @@ -63,6 +73,7 @@ type Realtime = {
getTimeout: () => number;
connect: () => void;
createSocket: () => void;
createHeartbeat: () => void;
cleanUp: (channels: string[]) => void;
onMessage: (event: MessageEvent) => void;
}
Expand Down Expand Up @@ -103,7 +114,7 @@ class Client {
'x-sdk-name': 'React Native',
'x-sdk-platform': 'client',
'x-sdk-language': 'reactnative',
'x-sdk-version': '0.5.0',
'x-sdk-version': '0.6.0',
'X-Appwrite-Response-Format': '1.6.0',
};

Expand Down Expand Up @@ -212,6 +223,7 @@ class Client {
private realtime: Realtime = {
socket: undefined,
timeout: undefined,
heartbeat: undefined,
url: '',
channels: new Set(),
subscriptions: new Map(),
Expand All @@ -237,6 +249,17 @@ class Client {
return 60_000;
}
},
createHeartbeat: () => {
if (this.realtime.heartbeat) {
clearTimeout(this.realtime.heartbeat);
}

this.realtime.heartbeat = window?.setInterval(() => {
this.realtime.socket?.send(JSON.stringify({
type: 'ping'
}));
}, 20_000);
},
createSocket: () => {
if (this.realtime.channels.size < 1) {
this.realtime.reconnect = false;
Expand Down Expand Up @@ -275,6 +298,7 @@ class Client {
this.realtime.socket.addEventListener('message', this.realtime.onMessage);
this.realtime.socket.addEventListener('open', _event => {
this.realtime.reconnectAttempts = 0;
this.realtime.createHeartbeat();
});
this.realtime.socket.addEventListener('close', event => {
if (
Expand Down

0 comments on commit bd5bb16

Please sign in to comment.