@@ -58,6 +58,8 @@ type Realtime = {
5858 }>;
5959 subscriptionsCounter: number;
6060 reconnect: boolean;
61+ reconnectAttempts: number;
62+ getTimeout: () => number;
6163 connect: () => void;
6264 createSocket: () => void;
6365 cleanUp: (channels: string[]) => void;
@@ -148,13 +150,26 @@ class {{ spec.title | caseUcfirst }} {
148150 subscriptions: new Map(),
149151 subscriptionsCounter: 0,
150152 reconnect: true,
153+ reconnectAttempts: 0,
151154 lastMessage: undefined,
152155 connect: () => {
153156 clearTimeout(this.realtime.timeout);
154157 this.realtime.timeout = window?.setTimeout(() => {
155158 this.realtime.createSocket();
156159 }, 50);
157160 },
161+ getTimeout: () => {
162+ switch (true) {
163+ case this.realtime.reconnectAttempts < 5:
164+ return 1000;
165+ case this.realtime.reconnectAttempts < 15:
166+ return 5000;
167+ case this.realtime.reconnectAttempts < 100:
168+ return 10_000;
169+ default:
170+ return 60_000;
171+ }
172+ },
158173 createSocket: () => {
159174 if (this.realtime.channels.size < 1) return;
160175 const channels = new URLSearchParams();
@@ -165,25 +180,31 @@ class {{ spec.title | caseUcfirst }} {
165180
166181 const url = this.config.endpointRealtime + '/realtime?' + channels.toString();
167182
168- if(url !== this.realtime.url || !this.realtime.socket || this.realtime.socket?.readyState > WebSocket.OPEN) {
169- if (this.realtime.socket && [WebSocket.OPEN, WebSocket.CONNECTING].includes( this.realtime.socket?.readyState) ) {
183+ if (url !== this.realtime.url || !this.realtime.socket || this.realtime.socket?.readyState > WebSocket.OPEN) {
184+ if (this.realtime.socket && this.realtime.socket?.readyState < WebSocket.CLOSING ) {
170185 this.realtime.reconnect = false;
171186 this.realtime.socket.close();
172187 }
173188
174189 this.realtime.url = url;
175190 this.realtime.socket = new WebSocket(url);
176191 this.realtime.socket.addEventListener('message', this.realtime.onMessage);
177-
192+ this.realtime.socket.addEventListener('open', event => {
193+ this.realtime.reconnectAttempts = 0;
194+ });
178195 this.realtime.socket.addEventListener('close', event => {
179196 if (!this.realtime.reconnect || (this.realtime?.lastMessage?.type === 'error' && (<RealtimeResponseError >this.realtime?.lastMessage.data).code === 1008)) {
180197 this.realtime.reconnect = true;
181198 return;
182199 }
183- console.error('Realtime got disconnected. Reconnect will be attempted in 1 second.', event.reason);
200+
201+ const timeout = this.realtime.getTimeout();
202+ console.error(`Realtime got disconnected. Reconnect will be attempted in ${timeout / 1000} seconds.`, event.reason);
203+
184204 setTimeout(() => {
205+ this.realtime.reconnectAttempts++;
185206 this.realtime.createSocket();
186- }, 1000 );
207+ }, timeout );
187208 })
188209 }
189210 },
0 commit comments