From cbea5d0d0fc8120e0970cac174335fbca52268b2 Mon Sep 17 00:00:00 2001 From: sockmaster27 <61235930+sockmaster27@users.noreply.github.com> Date: Thu, 22 Aug 2024 12:04:10 +0200 Subject: [PATCH] chore: make code more self-explanatory --- server/src/engine/socket.ts | 17 +++++++++-------- 1 file changed, 9 insertions(+), 8 deletions(-) diff --git a/server/src/engine/socket.ts b/server/src/engine/socket.ts index 17111e8..52ac414 100644 --- a/server/src/engine/socket.ts +++ b/server/src/engine/socket.ts @@ -90,26 +90,27 @@ export function initialiseSocket({ uri, onOpen, onClose }: InitialiseSocketInput WebSocket, }) - webSocket.addEventListener('open', function openHandler() { + webSocket.addEventListener('open', function handleOpen() { + // The 'open' event is emitted every time the connection is established, + // even if it was just a temprorary interruption. + // This handler should only be called once, so remove it after the first call. + webSocket.removeEventListener('open', handleOpen) + webSocketOpen = true - if (onOpen !== undefined) { - setTimeout(onOpen, 0) - } - webSocket.removeEventListener('open', openHandler) + onOpen?.() }) webSocket.addEventListener('close', () => { webSocketOpen = false + if (lastManualStopTimestamp + 15000 < Date.now()) { // This happens when the connections breaks unintentionally handleLostConnection() return } - if (onClose !== undefined) { - setTimeout(onClose, 0) - } + onClose?.() }) webSocket.addEventListener('message', message => {