70 lines
1.8 KiB
TypeScript
70 lines
1.8 KiB
TypeScript
import { SimplePool } from 'nostr-tools'
|
|
import type { Filter } from 'nostr-tools'
|
|
import type { Event } from 'nostr-tools'
|
|
|
|
/**
|
|
* Subscription interface matching nostr-tools 2.x API
|
|
*/
|
|
export interface Subscription {
|
|
on(event: 'event', callback: (event: Event) => void): void
|
|
on(event: 'eose', callback: () => void): void
|
|
unsub(): void
|
|
}
|
|
|
|
/**
|
|
* Type for SimplePool with subscribe method (for backward compatibility)
|
|
* Note: SimplePool already has subscribe method, this is just for type compatibility
|
|
*/
|
|
export type SimplePoolWithSub = SimplePool
|
|
|
|
/**
|
|
* Helper to create a subscription compatible with the old API
|
|
*/
|
|
export function createSubscription(
|
|
pool: SimplePool,
|
|
relays: string[],
|
|
filters: Filter[]
|
|
): Subscription {
|
|
const events: Event[] = []
|
|
let eoseReceived = false
|
|
const eventCallbacks: Array<(event: Event) => void> = []
|
|
const eoseCallbacks: Array<() => void> = []
|
|
|
|
const subscription = pool.subscribe(
|
|
relays,
|
|
filters[0] || {},
|
|
{
|
|
onevent: (event: Event) => {
|
|
events.push(event)
|
|
eventCallbacks.forEach((cb) => cb(event))
|
|
},
|
|
oneose: () => {
|
|
eoseReceived = true
|
|
eoseCallbacks.forEach((cb) => cb())
|
|
},
|
|
}
|
|
)
|
|
|
|
const subscriptionWrapper: Subscription = {
|
|
on(event: 'event' | 'eose', callback: ((event: Event) => void) | (() => void)): void {
|
|
if (event === 'event') {
|
|
const eventCb = callback as (event: Event) => void
|
|
eventCallbacks.push(eventCb)
|
|
// Emit any events that were already received
|
|
events.forEach((e) => eventCb(e))
|
|
} else if (event === 'eose') {
|
|
const eoseCb = callback as () => void
|
|
if (eoseReceived) {
|
|
eoseCb()
|
|
} else {
|
|
eoseCallbacks.push(eoseCb)
|
|
}
|
|
}
|
|
},
|
|
unsub(): void {
|
|
subscription.close()
|
|
},
|
|
}
|
|
return subscriptionWrapper
|
|
}
|