From 9e8aa162973ef993cd41c6c5bcfecef452fec925 Mon Sep 17 00:00:00 2001 From: daniyal Date: Wed, 18 Sep 2024 08:19:42 +0500 Subject: [PATCH] chore: fix relay controller --- src/controllers/relay.ts | 42 ++++++++++++++++++++++++++++++---------- 1 file changed, 32 insertions(+), 10 deletions(-) diff --git a/src/controllers/relay.ts b/src/controllers/relay.ts index 0b1413f..0811cd6 100644 --- a/src/controllers/relay.ts +++ b/src/controllers/relay.ts @@ -368,24 +368,46 @@ export class RelayController { */ fetchEvents = async ( filter: Filter, - relays: string[] = [] + relayUrls: string[] = [] ): Promise => { - // add app relay to relays array - relays.push(import.meta.env.VITE_APP_RELAY) + const relaySet = new Set() + + // add all the relays passed to relay set + relayUrls.forEach((relayUrl) => { + relaySet.add(relayUrl) + }) + + relaySet.add(import.meta.env.VITE_APP_RELAY) const metadataController = await MetadataController.getInstance() // add admin relays to relays array - metadataController.adminRelays.forEach((url) => { - relays.push(url) + metadataController.adminRelays.forEach((relayUrl) => { + relaySet.add(relayUrl) }) + relayUrls = Array.from(relaySet) + // Connect to all specified relays - const relayPromises = relays.map((relayUrl) => this.connectRelay(relayUrl)) - await Promise.allSettled(relayPromises) + const relayPromises = relayUrls.map((relayUrl) => + this.connectRelay(relayUrl) + ) + + // Use Promise.allSettled to wait for all promises to settle + const results = await Promise.allSettled(relayPromises) + + // Extract non-null values from fulfilled promises in a single pass + const relays = results.reduce((acc, result) => { + if (result.status === 'fulfilled') { + const value = result.value + if (value) { + acc.push(value) + } + } + return acc + }, []) // Check if any relays are connected - if (this.connectedRelays.length === 0) { - log(this.debug, LogType.Error, 'No relay is connected to fetch events!') + if (relays.length === 0) { throw new Error('No relay is connected to fetch events!') } @@ -393,7 +415,7 @@ export class RelayController { const eventIds = new Set() // To keep track of event IDs and avoid duplicates // Create a promise for each relay subscription - const subPromises = this.connectedRelays.map((relay) => { + const subPromises = relays.map((relay) => { return new Promise((resolve) => { // Subscribe to the relay with the specified filter const sub = relay.subscribe([filter], {