From 3caa4c31d1278bec6611ece6d0371eb557e947a2 Mon Sep 17 00:00:00 2001 From: Jonathan Staab Date: Mon, 7 Aug 2023 15:54:08 -0700 Subject: [PATCH] Allow reusing sockets by moving some logic to onClose --- package.json | 2 +- src/util/Socket.ts | 29 +++++++++++++++-------------- 2 files changed, 16 insertions(+), 15 deletions(-) diff --git a/package.json b/package.json index a3009b9..5a68c97 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "paravel", - "version": "0.2.2", + "version": "0.2.3", "description": "Yet another toolkit for nostr", "repository": { "type": "git", diff --git a/src/util/Socket.ts b/src/util/Socket.ts index 8d3bfbd..070223f 100644 --- a/src/util/Socket.ts +++ b/src/util/Socket.ts @@ -48,12 +48,24 @@ export class Socket extends EventEmitter { this.emit('fault', this) } onClose = () => { + if (this.ws) { + const ws = this.ws + + // Avoid "WebSocket was closed before the connection was established" + this.ready.then(() => ws.close(), () => null) + this.ws.removeEventListener("open", this.onOpen) + this.ws.removeEventListener("close", this.onClose) + this.ws.removeEventListener("error", this.onError) + // @ts-ignore + this.ws.removeEventListener("message", this.onMessage) + this.ws = undefined + } + if (this.status !== Socket.STATUS.ERROR) { - this.disconnect() - this.ready.reject() this.status = Socket.STATUS.CLOSED } + this.ready.reject() this.emit('close', this) } connect = () => { @@ -71,18 +83,7 @@ export class Socket extends EventEmitter { } } disconnect = () => { - if (this.ws) { - const ws = this.ws - - // Avoid "WebSocket was closed before the connection was established" - this.ready.then(() => ws.close(), () => null) - this.ws.removeEventListener("open", this.onOpen) - this.ws.removeEventListener("close", this.onClose) - this.ws.removeEventListener("error", this.onError) - // @ts-ignore - this.ws.removeEventListener("message", this.onMessage) - this.ws = undefined - } + this.onClose() } receiveMessage = (json: string) => { try {