From 281121b7cc2621a87e5a5e71e17f37a45e464320 Mon Sep 17 00:00:00 2001 From: Derrick Hammer Date: Tue, 31 Jan 2023 06:58:03 -0500 Subject: [PATCH] *Add basic eventemitter action queue to process once we have an active relay, or to immediately process if we already have one --- src/index.ts | 29 ++++++++++++++++++++++++----- 1 file changed, 24 insertions(+), 5 deletions(-) diff --git a/src/index.ts b/src/index.ts index 89e8d47..3f6c6b4 100644 --- a/src/index.ts +++ b/src/index.ts @@ -19,6 +19,7 @@ export default class HyperswarmWeb extends EventEmitter { private _relays: Set = new Set(); private _activeRelay: Hyperswarm; private _discovery: PeerDiscoveryClient; + private _queuedEmActions: [string, any][] = []; constructor(opts: any = {}) { super(); opts.custodial = false; @@ -75,6 +76,7 @@ export default class HyperswarmWeb extends EventEmitter { throw new Error("Failed to find an available relay"); } + this._processQueuedActions(); await this._activeRelay.dht.ready(); } @@ -124,7 +126,7 @@ export default class HyperswarmWeb extends EventEmitter { eventName: string | symbol, listener: (...args: any[]) => void ): Hyperswarm { - return this._activeRelay?.on(eventName, listener); + return this._processOrQueueAction("on", arguments); } addListener( eventName: string | symbol, @@ -137,20 +139,37 @@ export default class HyperswarmWeb extends EventEmitter { eventName: string | symbol, listener: (...args: any[]) => void ): Hyperswarm { - return this._activeRelay?.off(eventName, listener); + return this._processOrQueueAction("off", arguments); } removeListener( eventName: string | symbol, listener: (...args: any[]) => void ): this { - return this.on(eventName, listener); + return this.off(eventName, listener); } emit(eventName: string | symbol, ...args: any[]): boolean { - return this._activeRelay?.emit(eventName, ...args); + return this._processOrQueueAction("emit", arguments); } once(eventName: string | symbol, listener: (...args: any[]) => void): this { - return this._activeRelay?.once(eventName, listener); + return this._processOrQueueAction("once", arguments); + } + + private _processOrQueueAction(method: string, ...args: any[]) { + if (this._activeRelay) { + return this._activeRelay[method](...args); + } + + this._queuedEmActions.push([method, args]); + return this; + } + + private _processQueuedActions(): void { + for (const action of this._queuedEmActions) { + this._activeRelay[action[0]](...action[1]); + } + + this._queuedEmActions = []; } }