chore: add a map in relay controller for storing events

This commit is contained in:
daniyal 2024-09-02 13:44:58 +05:00
parent 0733849b25
commit c6831f3fb2

View File

@ -14,6 +14,7 @@ import { MetadataController, UserRelaysType } from './metadata'
*/
export class RelayController {
private static instance: RelayController
private events = new Map<string, Event>()
private debug = true
public connectedRelays: Relay[] = []
@ -151,6 +152,16 @@ export class RelayController {
// Wait for all publish operations to complete (either fulfilled or rejected)
await Promise.allSettled(publishPromises)
if (publishedOnRelays.length > 0) {
// if the event was successfully published to relays then check if it contains the `aTag`
// if so, then cache the event
const aTag = event.tags.find((item) => item[0] === 'a')
if (aTag && aTag[1]) {
this.events.set(aTag[1], event)
}
}
// Return the list of relay URLs where the event was published
return publishedOnRelays
}
@ -335,13 +346,35 @@ export class RelayController {
filter: Filter,
relays: string[] = []
): Promise<Event | null> => {
// first check if event is present in cached map then return that
// otherwise query relays
if (filter['#a']) {
const aTag = filter['#a'][0]
const cachedEvent = this.events.get(aTag)
if (cachedEvent) return cachedEvent
}
const events = await this.fetchEvents(filter, relays)
// Sort events by creation date in descending order
events.sort((a, b) => b.created_at - a.created_at)
// Return the most recent event, or null if no events were received
return events[0] || null
if (events.length > 0) {
const event = events[0]
// if the aTag was specified in filter then cache the fetched event before returning
if (filter['#a']) {
const aTag = filter['#a'][0]
this.events.set(aTag, event)
}
// return the event
return event
}
// return null if event array is empty
return null
}
/**
@ -358,6 +391,15 @@ export class RelayController {
hexKey: string,
userRelaysType: UserRelaysType
) => {
// first check if event is present in cached map then return that
// otherwise query relays
if (filter['#a']) {
const aTag = filter['#a'][0]
const cachedEvent = this.events.get(aTag)
if (cachedEvent) return cachedEvent
}
// Get an instance of the MetadataController, which manages user metadata and relays
const metadataController = await MetadataController.getInstance()