Skip to content

Commit

Permalink
feat: reconnect ws on abnormal disconnection
Browse files Browse the repository at this point in the history
  • Loading branch information
kirosc committed Aug 28, 2021
1 parent 16b47e0 commit da506d5
Show file tree
Hide file tree
Showing 3 changed files with 89 additions and 89 deletions.
132 changes: 59 additions & 73 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

18 changes: 9 additions & 9 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "3commas-typescript",
"version": "1.3.1",
"version": "1.3.2",
"description": "TypeScript 3Commas API client",
"repository": {
"type": "git",
Expand All @@ -27,21 +27,21 @@
"license": "MIT",
"devDependencies": {
"@types/crypto-js": "^4.0.2",
"@types/node": "^16.0.0",
"@types/qs": "^6.9.6",
"@types/ws": "^7.4.6",
"@types/node": "^16.7.4",
"@types/qs": "^6.9.7",
"@types/ws": "^7.4.7",
"dotenv": "^10.0.0",
"husky": "^7.0.1",
"lint-staged": "^11.0.0",
"husky": "^7.0.2",
"lint-staged": "^11.1.2",
"prettier": "^2.3.2",
"ts-node-dev": "^1.1.8",
"typescript": "^4.3.5"
"typescript": "^4.4.2"
},
"dependencies": {
"axios": "^0.21.1",
"crypto-js": "^4.0.0",
"crypto-js": "^4.1.1",
"qs": "^6.10.1",
"ws": "^7.5.2"
"ws": "^8.2.0"
},
"lint-staged": {
"*.{ts,json,md}": "prettier --write"
Expand Down
28 changes: 21 additions & 7 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import {
ThreeCommasError,
TransferHistoryParams,
TransferParams,
WebsocketCallback,
} from './types/types';
import { sign } from './lib/crypto';
import { Convert, Order } from './types/generated-types';
Expand Down Expand Up @@ -361,23 +362,36 @@ export class API {
private subscribe(
channel: Channel,
url: string,
callback?: (data: WebSocket.Data) => void
callback?: WebsocketCallback
) {
const payload = JSON.stringify({
identifier: this.buildIdentifier(channel, url),
command: 'subscribe',
});

if (!this.ws) {
const setUpWebsocketListener = (callback?: WebsocketCallback) => {
if (callback) {
this.ws?.on('message', (data: Buffer, isBinary: boolean) => {
const message = isBinary ? data : data.toString();
callback(message);
});
}
this.ws?.on('close', (code) => {
if (code === 1006) {
setUpWebsocket(payload);
}
});
};
const setUpWebsocket = (payload: string) => {
this.ws = new WebSocket(WS);
this.ws.onopen = () => this.ws?.send(payload);
setUpWebsocketListener(callback);
};

if (!this.ws) {
setUpWebsocket(payload);
} else {
this.ws.send(payload);
}

if (callback) {
this.ws.on('message', callback);
}
}

subscribeSmartTrade(callback?: (data: WebSocket.Data) => void) {
Expand Down

0 comments on commit da506d5

Please sign in to comment.