diff --git a/src/stats.ts b/src/stats.ts index 01b870ec..69182e8e 100644 --- a/src/stats.ts +++ b/src/stats.ts @@ -22,6 +22,9 @@ async function updateStats(event: NostrEvent) { prev = await maybeGetPrev(event); if (!prev || event.created_at >= prev.created_at) { queries.push(updateFollowingCountQuery(event)); + + const followersQuery = await updateFollowersCountQuery(event); + if (followersQuery) queries.push(followersQuery); } } @@ -179,6 +182,30 @@ function updateFollowingCountQuery({ pubkey, tags }: NostrEvent) { ); } +async function updateFollowersCountQuery({ tags }: NostrEvent) { + const userThatHasFollowersPub = tags.find(([name]) => name === 'p')?.[1]; + if (!userThatHasFollowersPub) return; + + const result = await eventsDB.query([{ kinds: [3], '#p': [userThatHasFollowersPub] }], { + signal: AbortSignal.timeout(1000), + }); + + if (result.length <= 0) return; + + return db.insertInto('author_stats') + .values({ + pubkey: userThatHasFollowersPub, + following_count: 0, + followers_count: result.length, + notes_count: 0, + }) + .onConflict((oc) => + oc + .column('pubkey') + .doUpdateSet({ followers_count: result.length }) + ); +} + /** Compare the old and new follow events (if any), and return a diff array. */ function getFollowDiff(event: NostrEvent, prev?: NostrEvent): AuthorStatDiff[] { const prevTags = prev?.tags ?? [];