diff --git a/package.json b/package.json index cc17ac8..b4dc95a 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "bybit-api", - "version": "3.0.2", + "version": "3.1.0", "description": "Complete & robust node.js SDK for Bybit's REST APIs and WebSockets, with TypeScript & integration tests.", "main": "lib/index.js", "types": "lib/index.d.ts", diff --git a/src/websocket-client.ts b/src/websocket-client.ts index 4e145a2..f7063ce 100644 --- a/src/websocket-client.ts +++ b/src/websocket-client.ts @@ -116,22 +116,21 @@ export class WebsocketClient extends EventEmitter { public subscribe(wsTopics: WsTopic[] | WsTopic, isPrivateTopic?: boolean) { const topics = Array.isArray(wsTopics) ? wsTopics : [wsTopics]; - topics.forEach((topic) => - this.wsStore.addTopic( - getWsKeyForTopic(this.options.market, topic, isPrivateTopic), - topic - ) - ); + topics.forEach((topic) => { + const wsKey = getWsKeyForTopic( + this.options.market, + topic, + isPrivateTopic + ); + + // Persist topic for reconnects + this.wsStore.addTopic(wsKey, topic); - // attempt to send subscription topic per websocket - this.wsStore.getKeys().forEach((wsKey: WsKey) => { // if connected, send subscription request if ( this.wsStore.isConnectionState(wsKey, WsConnectionStateEnum.CONNECTED) ) { - return this.requestSubscribeTopics(wsKey, [ - ...this.wsStore.getTopics(wsKey), - ]); + return this.requestSubscribeTopics(wsKey, [topic]); } // start connection process if it hasn't yet begun. Topics are automatically subscribed to on-connect @@ -157,21 +156,21 @@ export class WebsocketClient extends EventEmitter { */ public unsubscribe(wsTopics: WsTopic[] | WsTopic, isPrivateTopic?: boolean) { const topics = Array.isArray(wsTopics) ? wsTopics : [wsTopics]; - topics.forEach((topic) => - this.wsStore.deleteTopic( - getWsKeyForTopic(this.options.market, topic, isPrivateTopic), - topic - ) - ); + topics.forEach((topic) => { + const wsKey = getWsKeyForTopic( + this.options.market, + topic, + isPrivateTopic + ); + + // Remove topic from persistence for reconnects + this.wsStore.deleteTopic(wsKey, topic); - this.wsStore.getKeys().forEach((wsKey: WsKey) => { // unsubscribe request only necessary if active connection exists if ( this.wsStore.isConnectionState(wsKey, WsConnectionStateEnum.CONNECTED) ) { - this.requestUnsubscribeTopics(wsKey, [ - ...this.wsStore.getTopics(wsKey), - ]); + this.requestUnsubscribeTopics(wsKey, [topic]); } }); }