Exponential backoff on reconnect.

This commit is contained in:
Paul Makles
2020-12-31 13:04:49 +00:00
parent 715c532634
commit e6465d0646
5 changed files with 26 additions and 1 deletions
+1
View File
@@ -8,6 +8,7 @@
"dependencies": {
"axios": "^0.19.2",
"concurrently": "^5.1.0",
"exponential-backoff": "^3.1.0",
"isomorphic-ws": "^4.0.1",
"lodash": "^4.17.15",
"tsc-watch": "^4.1.0",
+1
View File
@@ -21,6 +21,7 @@ export interface ClientOptions {
export declare interface Client {
// WebSocket related events.
on(event: 'connected', listener: () => void): this;
on(event: 'connecting', listener: () => void): this;
on(event: 'dropped', listener: () => void): this;
on(event: 'ready', listener: () => void): this;
}
+12
View File
@@ -8,6 +8,18 @@ client.on('ready', () => {
console.log(`Logged in as @${client.user?.username}`);
});
client.on('connecting', () => {
console.log(`Connecting to the notifications server.`);
});
client.on('connected', () => {
console.log(`Connected to notifications server.`);
});
client.on('dropped', () => {
console.log(`Connection dropped.`);
});
(async () => {
console.log('Start:', new Date());
+7 -1
View File
@@ -1,4 +1,5 @@
import WebSocket from 'isomorphic-ws';
import { backOff } from 'exponential-backoff';
import { Client } from '..';
import { Auth } from '../api/auth';
@@ -14,7 +15,9 @@ export class WebSocketClient {
this.client = client;
}
connect(): Promise<void> {
connect(disallowReconnect?: boolean): Promise<void> {
this.client.emit('connecting');
return new Promise((resolve, $reject) => {
let thrown = false;
const reject = (err: any) => {
@@ -63,6 +66,9 @@ export class WebSocketClient {
ws.onclose = () => {
this.client.emit('dropped');
if (!disallowReconnect && this.client.options.autoReconnect) {
backOff(() => this.connect(true)).catch(reject);
}
};
});
}
+5
View File
@@ -164,6 +164,11 @@ event-stream@=3.3.4:
stream-combiner "~0.0.4"
through "~2.3.1"
exponential-backoff@^3.1.0:
version "3.1.0"
resolved "https://registry.yarnpkg.com/exponential-backoff/-/exponential-backoff-3.1.0.tgz#9409c7e579131f8bd4b32d7d8094a911040f2e68"
integrity sha512-oBuz5SYz5zzyuHINoe9ooePwSu0xApKWgeNzok4hZ5YKXFh9zrQBEM15CXqoZkJJPuI2ArvqjPQd8UKJA753XA==
find-up@^3.0.0:
version "3.0.0"
resolved "https://registry.yarnpkg.com/find-up/-/find-up-3.0.0.tgz#49169f1d7993430646da61ecc5ae355c21c97b73"