Relay Pool ​
The NPool class is an NRelay implementation for connecting to multiple relays.
Usage ​
This class is designed with the Outbox model in mind.
Instead of passing relay URLs into each method, you pass functions into the constructor that statically-analyze filters and events to determine which relays to use for requesting and publishing events.
const pool = new NPool({
open(url) {
return new NRelay1(url);
},
async reqRouter(filters) {
return new Map([
['wss://relay.damus.io', filters],
['wss://nos.lol', filters],
]);
},
async eventRouter(event) {
return ['wss://relay.damus.io', 'wss://nos.lol'];
},
});
// Now you can use the pool like a regular relay.
for await (const msg of pool.req([{ kinds: [1] }])) {
if (msg[0] === 'EVENT') console.log(msg[2]);
if (msg[0] === 'EOSE') break;
}INFO
- If a relay wasn't already connected, it will be opened automatically. Defining
openwill also let you use any relay implementation, such asNRelay1. pool.reqmay stream duplicate events, whilepool.querywill correctly process replaceable events and deletions within the event set before returning them.pool.reqwill only emit anEOSEwhen all relays in its set have emitted anEOSE, and likewise forCLOSED.
Options ​
open- A function like(url: string) => NRelay. This function should return a new instance ofNRelayfor the given URL.reqRouter- A function like(filters: NostrFilter[]) => ReadonlyMap<string, NostrFilter[]> | Promise<ReadonlyMap<string, NostrFilter[]>>. Returns a map of relay URLs to the filters that should be sent to each relay. To support the Outbox model, it should analyze theauthorsfield of the filters.eventRouter- A function like(event: NostrEvent) => string[] | Promise<string[]>. Returns an array of relay URLs to use for publishing an EVENT. To support the Outbox model, it should analyze thepubkeyfield of the event.eoseTimeout- Maximum time in milliseconds to wait for remaining relays after the first EOSE is received inquery(). Defaults to1000ms. Set to0to disable timeout and wait for all relays.
TIP
The url parameter is a unique relay identifier (string), and doesn't technically have to be a URL, as long as you handle it correctly in your open function.
Performance ​
By default, pool.query() will wait up to 1 second after the first relay sends EOSE before canceling slow relays. This prevents slow relays from degrading the performance of queries. You can customize this timeout using the eoseTimeout option, or disable it by setting it to 0. This timeout does not affect pool.req(), which will always wait for all relays.