64 lines
1.7 KiB
TypeScript
64 lines
1.7 KiB
TypeScript
import type { Event } from 'nostr-tools'
|
|
import { nostrService } from './nostr'
|
|
import type { Review } from '@/types/nostr'
|
|
import { parseReviewFromEvent } from './nostrEventParsing'
|
|
import { buildTagFilter } from './nostrTagSystem'
|
|
import { getPrimaryRelaySync } from './config'
|
|
|
|
function buildReviewFilters(articleId: string) {
|
|
const tagFilter = buildTagFilter({
|
|
type: 'quote',
|
|
articleId,
|
|
})
|
|
|
|
const filterObj: {
|
|
kinds: number[]
|
|
'#quote'?: string[]
|
|
'#article'?: string[]
|
|
} = {
|
|
kinds: Array.isArray(tagFilter.kinds) ? tagFilter.kinds as number[] : [1],
|
|
}
|
|
if (tagFilter['#quote']) {
|
|
filterObj['#quote'] = tagFilter['#quote'] as string[]
|
|
}
|
|
if (tagFilter['#article']) {
|
|
filterObj['#article'] = tagFilter['#article'] as string[]
|
|
}
|
|
return [filterObj]
|
|
}
|
|
|
|
export function getReviewsForArticle(articleId: string, timeoutMs: number = 5000): Promise<Review[]> {
|
|
const pool = nostrService.getPool()
|
|
if (!pool) {
|
|
throw new Error('Pool not initialized')
|
|
}
|
|
const filters = buildReviewFilters(articleId)
|
|
const { createSubscription } = require('@/types/nostr-tools-extended')
|
|
|
|
return new Promise<Review[]>((resolve) => {
|
|
const results: Review[] = []
|
|
const relayUrl = getPrimaryRelaySync()
|
|
const sub = createSubscription(pool, [relayUrl], filters)
|
|
let finished = false
|
|
|
|
const done = () => {
|
|
if (finished) {
|
|
return
|
|
}
|
|
finished = true
|
|
sub.unsub()
|
|
resolve(results)
|
|
}
|
|
|
|
sub.on('event', (event: Event) => {
|
|
const parsed = parseReviewFromEvent(event)
|
|
if (parsed) {
|
|
results.push(parsed)
|
|
}
|
|
})
|
|
|
|
sub.on('eose', () => done())
|
|
setTimeout(() => done(), timeoutMs).unref?.()
|
|
})
|
|
}
|