Skip to content

Commit d4f1bb4

Browse files
committed
Set listeners once only
1 parent 2e2767a commit d4f1bb4

File tree

1 file changed

+28
-25
lines changed

1 file changed

+28
-25
lines changed

src/client/Websocket.ts

+28-25
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,31 @@ export class WebsocketClient extends EventEmitter {
4646
}).bind(undefined, this.getToken, this);
4747

4848
this.setToken(auth.token).connect(auth.socket);
49+
50+
// Set listerners
51+
this.on('daemon error', (message) => {
52+
console.error(message);
53+
});
54+
55+
this.on('token expiring', () => this.updateToken());
56+
this.on('token expired', () => this.updateToken());
57+
this.on('jwt error', (error: string) => {
58+
if (reconnectErrors.find((v) => error.toLowerCase().indexOf(v) >= 0)) {
59+
this.updateToken();
60+
} else {
61+
throw new Error(error);
62+
}
63+
});
64+
this.on('transfer status', (status: string) => {
65+
if (status === 'starting' || status === 'success') {
66+
return;
67+
}
68+
69+
// This code forces a reconnection to the websocket which will connect us to the target node instead of the source node
70+
// in order to be able to receive transfer logs from the target node.
71+
this.close();
72+
this.open();
73+
});
4974
}
5075

5176
private isUpdating = false;
@@ -73,9 +98,11 @@ export class WebsocketClient extends EventEmitter {
7398
private connect(url: string): this {
7499
this.url = url;
75100

101+
this.timer && clearTimeout(this.timer);
102+
76103
// Close socket if needed
77104
if (this.socket?.ws.OPEN) {
78-
this.socket.close();
105+
this.close();
79106
}
80107

81108
this.socket = new Socket(this.url, {
@@ -113,30 +140,6 @@ export class WebsocketClient extends EventEmitter {
113140
}
114141
});
115142

116-
this.on('daemon error', (message) => {
117-
console.error(message);
118-
});
119-
120-
this.on('token expiring', () => this.updateToken());
121-
this.on('token expired', () => this.updateToken());
122-
this.on('jwt error', (error: string) => {
123-
if (reconnectErrors.find((v) => error.toLowerCase().indexOf(v) >= 0)) {
124-
this.updateToken();
125-
} else {
126-
throw new Error(error);
127-
}
128-
});
129-
this.on('transfer status', (status: string) => {
130-
if (status === 'starting' || status === 'success') {
131-
return;
132-
}
133-
134-
// This code forces a reconnection to the websocket which will connect us to the target node instead of the source node
135-
// in order to be able to receive transfer logs from the target node.
136-
this.close();
137-
this.open();
138-
});
139-
140143
this.timer = setTimeout(() => {
141144
this.backoff = this.backoff + 2500 >= 20000 ? 20000 : this.backoff + 2500;
142145
this.socket && this.socket.close(undefined, 'timeout');

0 commit comments

Comments
 (0)