Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(v1.5.6): add safeTerminate method with fallback for browsers #98

Merged
merged 1 commit into from
Feb 23, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions package-lock.json

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

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "okx-api",
"version": "1.5.5",
"version": "1.5.6",
"description": "Complete & robust Node.js SDK for OKX's REST APIs and WebSockets, with TypeScript & end-to-end tests",
"main": "lib/index.js",
"types": "lib/index.d.ts",
Expand Down
22 changes: 22 additions & 0 deletions src/util/websocket-util.ts
Original file line number Diff line number Diff line change
Expand Up @@ -329,3 +329,25 @@ export const WS_EVENT_CODE_ENUM = {
LOGIN_FAILED: '60009',
LOGIN_PARTIALLY_FAILED: '60022',
};

/**
* #305: ws.terminate() is undefined in browsers.
* This only works in node.js, not in browsers.
* Does nothing if `ws` is undefined. Does nothing in browsers.
*/
export function safeTerminateWs(
ws?: WebSocket | any,
fallbackToClose?: boolean,
): boolean {
if (!ws) {
return false;
}
if (typeof ws['terminate'] === 'function') {
ws.terminate();
return true;
} else if (fallbackToClose) {
ws.close();
}

return false;
}
7 changes: 5 additions & 2 deletions src/websocket-client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ import { signMessage } from './util/node-support';
import {
getWsKeyForMarket,
getWsUrlForWsKey,
safeTerminateWs,
WS_EVENT_CODE_ENUM,
WsKey,
} from './util/websocket-util';
Expand Down Expand Up @@ -196,7 +197,7 @@ export class WebsocketClient extends EventEmitter {
const ws = this.wsStore.getWs(wsKey);
ws?.close();
if (force) {
ws?.terminate();
safeTerminateWs(ws);
}
}

Expand Down Expand Up @@ -484,8 +485,10 @@ export class WebsocketClient extends EventEmitter {
});

const wasOpen = this.wsStore.isWsOpen(wsKey);
if (wasOpen) {
safeTerminateWs(this.wsStore.getWs(wsKey), true);
}

this.wsStore.getWs(wsKey)?.terminate();
delete this.wsStore.get(wsKey, true).activePongTimer;
this.clearPingTimer(wsKey);
this.clearPongTimer(wsKey);
Expand Down
Loading