87 lines
2.1 KiB
TypeScript
87 lines
2.1 KiB
TypeScript
import type { Event } from 'nostr-tools'
|
|
import { nostrService } from './nostr'
|
|
import type { SimplePoolWithSub } from '@/types/nostr-tools-extended'
|
|
import type { Series } from '@/types/nostr'
|
|
import { parseSeriesFromEvent } from './nostrEventParsing'
|
|
|
|
const RELAY_URL = process.env.NEXT_PUBLIC_NOSTR_RELAY_URL ?? 'wss://relay.damus.io'
|
|
|
|
export function getSeriesByAuthor(authorPubkey: string, timeoutMs: number = 5000): Promise<Series[]> {
|
|
const pool = nostrService.getPool()
|
|
if (!pool) {
|
|
throw new Error('Pool not initialized')
|
|
}
|
|
const poolWithSub = pool as SimplePoolWithSub
|
|
const filters = [
|
|
{
|
|
kinds: [1],
|
|
authors: [authorPubkey],
|
|
'#kind_type': ['series'],
|
|
},
|
|
]
|
|
|
|
return new Promise<Series[]>((resolve) => {
|
|
const results: Series[] = []
|
|
const sub = poolWithSub.sub([RELAY_URL], filters)
|
|
let finished = false
|
|
|
|
const done = () => {
|
|
if (finished) {
|
|
return
|
|
}
|
|
finished = true
|
|
sub.unsub()
|
|
resolve(results)
|
|
}
|
|
|
|
sub.on('event', (event: Event) => {
|
|
const parsed = parseSeriesFromEvent(event)
|
|
if (parsed) {
|
|
results.push(parsed)
|
|
}
|
|
})
|
|
|
|
sub.on('eose', () => done())
|
|
setTimeout(() => done(), timeoutMs).unref?.()
|
|
})
|
|
}
|
|
|
|
export function getSeriesById(seriesId: string, timeoutMs: number = 5000): Promise<Series | null> {
|
|
const pool = nostrService.getPool()
|
|
if (!pool) {
|
|
throw new Error('Pool not initialized')
|
|
}
|
|
const poolWithSub = pool as SimplePoolWithSub
|
|
const filters = [
|
|
{
|
|
kinds: [1],
|
|
ids: [seriesId],
|
|
'#kind_type': ['series'],
|
|
},
|
|
]
|
|
|
|
return new Promise<Series | null>((resolve) => {
|
|
const sub = poolWithSub.sub([RELAY_URL], filters)
|
|
let finished = false
|
|
|
|
const done = (value: Series | null) => {
|
|
if (finished) {
|
|
return
|
|
}
|
|
finished = true
|
|
sub.unsub()
|
|
resolve(value)
|
|
}
|
|
|
|
sub.on('event', (event: Event) => {
|
|
const parsed = parseSeriesFromEvent(event)
|
|
if (parsed) {
|
|
done(parsed)
|
|
}
|
|
})
|
|
|
|
sub.on('eose', () => done(null))
|
|
setTimeout(() => done(null), timeoutMs).unref?.()
|
|
})
|
|
}
|