From 290ca18c4bd8bae0c945f135769572fb83964dca Mon Sep 17 00:00:00 2001 From: Derrick Hammer Date: Sun, 19 Mar 2023 14:02:50 -0400 Subject: [PATCH] *Store the listenConnections connection so don't create duplicates incase init/ready is called multiple times --- src/index.ts | 39 +++++++++++++++++++++++---------------- 1 file changed, 23 insertions(+), 16 deletions(-) diff --git a/src/index.ts b/src/index.ts index 894ff19..6496638 100644 --- a/src/index.ts +++ b/src/index.ts @@ -15,6 +15,10 @@ export class SwarmClient extends Client { private _connectBackoff: any; private _ready?: Promise; + private _connectionListener?: [ + sendUpdate: DataFn, + response: Promise + ]; private _topics: Set = new Set(); private _sockets: Map = new Map(); @@ -87,26 +91,29 @@ export class SwarmClient extends Client { } private async _listen() { - const connect = this.connectModule( - "listenConnections", - { swarm: this.swarm }, - async (socketId: any) => { - const socket = - this._sockets.get(socketId) ?? (await createSocket(socketId)); + if (!this._connectionListener) { + this._connectionListener = this.connectModule( + "listenConnections", + { swarm: this.swarm }, + async (socketId: any) => { + const socket = + this._sockets.get(socketId) ?? (await createSocket(socketId)); - socket.on("close", () => { - this._sockets.delete(socketId); - }); + socket.on("close", () => { + this._sockets.delete(socketId); + }); - if (!this._sockets.has(socketId)) { - this._sockets.set(socketId, socket); + if (!this._sockets.has(socketId)) { + this._sockets.set(socketId, socket); + } + + this.emit("connection", socket); } + ); + } - this.emit("connection", socket); - } - ); - - await connect[1]; + await this._connectionListener[1]; + this._connectionListener = undefined; this.start(); }