Allow reusing sockets by moving some logic to onClose

This commit is contained in:
Jonathan Staab
2023-08-07 15:54:08 -07:00
parent 5d86ec639e
commit 3caa4c31d1
2 changed files with 16 additions and 15 deletions
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "paravel",
"version": "0.2.2",
"version": "0.2.3",
"description": "Yet another toolkit for nostr",
"repository": {
"type": "git",
+15 -14
View File
@@ -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 {