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 ( fetchEvents = async (
filter: Filter, filter: Filter,
relays: string[] = [] relayUrls: string[] = []
): Promise<Event[]> => { ): Promise<Event[]> => {
// add app relay to relays array const relaySet = new Set<string>()
relays.push(import.meta.env.VITE_APP_RELAY)
// 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() const metadataController = await MetadataController.getInstance()
// add admin relays to relays array // add admin relays to relays array
metadataController.adminRelays.forEach((url) => { metadataController.adminRelays.forEach((relayUrl) => {
relays.push(url) relaySet.add(relayUrl)
}) })
relayUrls = Array.from(relaySet)
// Connect to all specified relays // Connect to all specified relays
const relayPromises = relays.map((relayUrl) => this.connectRelay(relayUrl)) const relayPromises = relayUrls.map((relayUrl) =>
await Promise.allSettled(relayPromises) 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 // Check if any relays are connected
if (this.connectedRelays.length === 0) { if (relays.length === 0) {
log(this.debug, LogType.Error, 'No relay is connected to fetch events!')
throw new Error('No relay is connected to fetch events!') 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 const eventIds = new Set<string>() // To keep track of event IDs and avoid duplicates
// Create a promise for each relay subscription // Create a promise for each relay subscription
const subPromises = this.connectedRelays.map((relay) => { const subPromises = relays.map((relay) => {
return new Promise<void>((resolve) => { return new Promise<void>((resolve) => {
// Subscribe to the relay with the specified filter // Subscribe to the relay with the specified filter
const sub = relay.subscribe([filter], { const sub = relay.subscribe([filter], {