Skip to content

Commit

Permalink
fix(legacy-ws): clean websocket pointer if the connection is closed
Browse files Browse the repository at this point in the history
  • Loading branch information
ardatan committed Jun 12, 2023
1 parent cb78224 commit 621d848
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 10 deletions.
5 changes: 5 additions & 0 deletions .changeset/fifty-games-reflect.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@graphql-tools/executor-legacy-ws': patch
---

Clean websocket pointer if the connection is closed
24 changes: 14 additions & 10 deletions packages/executors/legacy-ws/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { ExecutionRequest, ExecutionResult, Executor, observableToAsyncIterable, Observer } from '@graphql-tools/utils';
import { ExecutionRequest, Executor, observableToAsyncIterable } from '@graphql-tools/utils';
import { print } from 'graphql';
import WebSocket from 'isomorphic-ws';

Expand All @@ -25,8 +25,6 @@ export function buildWSLegacyExecutor(
WebSocketImpl: typeof WebSocket,
options?: LegacyWSExecutorOpts
): Executor {
const observerById = new Map<string, Observer<ExecutionResult<any>>>();

let websocket: WebSocket | null = null;

const ensureWebsocket = () => {
Expand Down Expand Up @@ -54,10 +52,14 @@ export function buildWSLegacyExecutor(
})
);
};

websocket.onclose = () => {
websocket = null;
};
};

const cleanupWebsocket = () => {
if (websocket != null && observerById.size === 0) {
if (websocket != null) {
websocket.send(
JSON.stringify({
type: LEGACY_WS.CONNECTION_TERMINATE,
Expand Down Expand Up @@ -125,12 +127,14 @@ export function buildWSLegacyExecutor(

return {
unsubscribe: () => {
websocket?.send(
JSON.stringify({
type: LEGACY_WS.STOP,
id,
})
);
if (websocket?.readyState === WebSocket.OPEN) {
websocket?.send(
JSON.stringify({
type: LEGACY_WS.STOP,
id,
})
);
}
cleanupWebsocket();
},
};
Expand Down

0 comments on commit 621d848

Please sign in to comment.