Skip to content

Commit

Permalink
Set listeners once only
Browse files Browse the repository at this point in the history
  • Loading branch information
Linux123123 committed Nov 27, 2023
1 parent 2e2767a commit d4f1bb4
Showing 1 changed file with 28 additions and 25 deletions.
53 changes: 28 additions & 25 deletions src/client/Websocket.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,31 @@ export class WebsocketClient extends EventEmitter {
}).bind(undefined, this.getToken, this);

this.setToken(auth.token).connect(auth.socket);

// Set listerners
this.on('daemon error', (message) => {
console.error(message);
});

this.on('token expiring', () => this.updateToken());
this.on('token expired', () => this.updateToken());
this.on('jwt error', (error: string) => {
if (reconnectErrors.find((v) => error.toLowerCase().indexOf(v) >= 0)) {
this.updateToken();
} else {
throw new Error(error);
}
});
this.on('transfer status', (status: string) => {
if (status === 'starting' || status === 'success') {
return;
}

// This code forces a reconnection to the websocket which will connect us to the target node instead of the source node
// in order to be able to receive transfer logs from the target node.
this.close();
this.open();
});
}

private isUpdating = false;
Expand Down Expand Up @@ -73,9 +98,11 @@ export class WebsocketClient extends EventEmitter {
private connect(url: string): this {
this.url = url;

this.timer && clearTimeout(this.timer);

// Close socket if needed
if (this.socket?.ws.OPEN) {
this.socket.close();
this.close();
}

this.socket = new Socket(this.url, {
Expand Down Expand Up @@ -113,30 +140,6 @@ export class WebsocketClient extends EventEmitter {
}
});

this.on('daemon error', (message) => {
console.error(message);
});

this.on('token expiring', () => this.updateToken());
this.on('token expired', () => this.updateToken());
this.on('jwt error', (error: string) => {
if (reconnectErrors.find((v) => error.toLowerCase().indexOf(v) >= 0)) {
this.updateToken();
} else {
throw new Error(error);
}
});
this.on('transfer status', (status: string) => {
if (status === 'starting' || status === 'success') {
return;
}

// This code forces a reconnection to the websocket which will connect us to the target node instead of the source node
// in order to be able to receive transfer logs from the target node.
this.close();
this.open();
});

this.timer = setTimeout(() => {
this.backoff = this.backoff + 2500 >= 20000 ? 20000 : this.backoff + 2500;
this.socket && this.socket.close(undefined, 'timeout');
Expand Down

0 comments on commit d4f1bb4

Please sign in to comment.