story-research-zapwall/lib/articleQueries.ts

55 lines
1.5 KiB
TypeScript

import type { Event } from 'nostr-tools'
import { nostrService } from './nostr'
import { SimplePool } from 'nostr-tools'
import { createSubscription } from '@/types/nostr-tools-extended'
import type { Article } from '@/types/nostr'
import { parseArticleFromEvent } from './nostrEventParsing'
import { buildTagFilter } from './nostrTagSystem'
import { getPrimaryRelaySync } from './config'
function createSeriesSubscription(pool: SimplePool, seriesId: string, limit: number) {
const filters = [
{
...buildTagFilter({
type: 'publication',
seriesId,
}),
limit,
},
]
const relayUrl = getPrimaryRelaySync()
return createSubscription(pool, [relayUrl], filters)
}
export function getArticlesBySeries(seriesId: string, timeoutMs: number = 5000, limit: number = 100): Promise<Article[]> {
const pool = nostrService.getPool()
if (!pool) {
throw new Error('Pool not initialized')
}
const sub = createSeriesSubscription(pool, seriesId, limit)
return new Promise<Article[]>((resolve) => {
const results: Article[] = []
let finished = false
const done = () => {
if (finished) {
return
}
finished = true
sub.unsub()
resolve(results)
}
sub.on('event', (event: Event) => {
const parsed = parseArticleFromEvent(event)
if (parsed) {
results.push(parsed)
}
})
sub.on('eose', () => done())
setTimeout(() => done(), timeoutMs).unref?.()
})
}