chore: fix relay controller

This commit is contained in:
daniyal 2024-09-18 08:19:42 +05:00
parent a90e932ed6
commit 9e8aa16297

View File

@ -368,24 +368,46 @@ export class RelayController {
*/
fetchEvents = async (
filter: Filter,
relays: string[] = []
relayUrls: string[] = []
): Promise<Event[]> => {
// add app relay to relays array
relays.push(import.meta.env.VITE_APP_RELAY)
const relaySet = new Set<string>()
// 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<Relay[]>((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<string>() // 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<void>((resolve) => {
// Subscribe to the relay with the specified filter
const sub = relay.subscribe([filter], {