make pool.subscribe_ methods return synchronously.

This commit is contained in:
fiatjaf
2023-12-18 09:53:06 -03:00
parent 73c6630cf7
commit 9e4911160a

27
pool.ts
View File

@@ -4,6 +4,8 @@ import { normalizeURL } from './utils.ts'
import type { Event } from './event.ts' import type { Event } from './event.ts'
import { type Filter } from './filter.ts' import { type Filter } from './filter.ts'
export type SubCloser = { close: () => void }
export type SubscribeManyParams = Omit<SubscriptionParams, 'onclose' | 'id'> & { export type SubscribeManyParams = Omit<SubscriptionParams, 'onclose' | 'id'> & {
eoseSubTimeout?: number eoseSubTimeout?: number
onclose?: (reasons: string[]) => void onclose?: (reasons: string[]) => void
@@ -27,11 +29,7 @@ export class SimplePool {
return relay return relay
} }
async subscribeMany( subscribeMany(relays: string[], filters: Filter[], params: SubscribeManyParams): SubCloser {
relays: string[],
filters: Filter[],
params: SubscribeManyParams,
): Promise<{ close: () => void }> {
if (this.trackRelays) { if (this.trackRelays) {
params.receivedEvent = (relay: Relay, id: string) => { params.receivedEvent = (relay: Relay, id: string) => {
let set = this.seenOn.get(id) let set = this.seenOn.get(id)
@@ -80,7 +78,7 @@ export class SimplePool {
} }
// open a subscription in all given relays // open a subscription in all given relays
await Promise.all( const allOpened = Promise.all(
relays.map(normalizeURL).map(async (url, i, arr) => { relays.map(normalizeURL).map(async (url, i, arr) => {
if (arr.indexOf(url) !== i) { if (arr.indexOf(url) !== i) {
// duplicate // duplicate
@@ -108,7 +106,8 @@ export class SimplePool {
) )
return { return {
close() { async close() {
await allOpened
subs.forEach(sub => { subs.forEach(sub => {
sub.close() sub.close()
}) })
@@ -116,20 +115,18 @@ export class SimplePool {
} }
} }
async subscribeManyEose( subscribeManyEose(
relays: string[], relays: string[],
filters: Filter[], filters: Filter[],
params: Pick<SubscribeManyParams, 'id' | 'onevent' | 'onclose' | 'eoseSubTimeout'>, params: Pick<SubscribeManyParams, 'id' | 'onevent' | 'onclose' | 'eoseSubTimeout'>,
): Promise<{ close: () => void }> { ): SubCloser {
const sub = await this.subscribeMany(relays, filters, { const subcloser = this.subscribeMany(relays, filters, {
...params, ...params,
oneose() { oneose() {
setTimeout(() => { subcloser.close()
sub.close()
}, 0)
}, },
}) })
return sub return subcloser
} }
async querySync( async querySync(
@@ -139,7 +136,7 @@ export class SimplePool {
): Promise<Event[]> { ): Promise<Event[]> {
return new Promise(async resolve => { return new Promise(async resolve => {
const events: Event[] = [] const events: Event[] = []
await this.subscribeManyEose(relays, [filter], { this.subscribeManyEose(relays, [filter], {
...params, ...params,
onevent(event: Event) { onevent(event: Event) {
events.push(event) events.push(event)