diff --git a/src/utils/stats.test.ts b/src/utils/stats.test.ts index 2d3eaca..17f36c0 100644 --- a/src/utils/stats.test.ts +++ b/src/utils/stats.test.ts @@ -2,7 +2,7 @@ import { assertEquals } from '@std/assert'; import { generateSecretKey, getPublicKey } from 'nostr-tools'; import { genEvent, getTestDB } from '@/test.ts'; -import { getAuthorStats, getEventStats, getFollowDiff, updateStats } from '@/utils/stats.ts'; +import { countAuthorStats, getAuthorStats, getEventStats, getFollowDiff, updateStats } from '@/utils/stats.ts'; Deno.test('updateStats with kind 1 increments notes count', async () => { await using db = await getTestDB(); @@ -142,3 +142,19 @@ Deno.test('updateStats with kind 5 decrements reactions count', async () => { assertEquals(stats!.reactions_count, 0); }); + +Deno.test('countAuthorStats counts author stats from the database', async () => { + await using db = await getTestDB(); + + const sk = generateSecretKey(); + const pubkey = getPublicKey(sk); + + await db.store.event(genEvent({ kind: 1, content: 'hello' }, sk)); + await db.store.event(genEvent({ kind: 1, content: 'yolo' }, sk)); + await db.store.event(genEvent({ kind: 3, tags: [['p', pubkey]] })); + + const stats = await countAuthorStats(db.store, pubkey); + + assertEquals(stats!.notes_count, 2); + assertEquals(stats!.followers_count, 1); +}); diff --git a/src/utils/stats.ts b/src/utils/stats.ts index 306bdab..2652cbe 100644 --- a/src/utils/stats.ts +++ b/src/utils/stats.ts @@ -1,5 +1,6 @@ import { NostrEvent, NStore } from '@nostrify/nostrify'; import { Kysely, UpdateObject } from 'kysely'; +import { SetRequired } from 'type-fest'; import { DittoTables } from '@/db/DittoTables.ts'; import { getTagSet } from '@/utils/tags.ts'; @@ -176,3 +177,22 @@ export async function updateEventStats( .execute(); } } + +/** Calculate author stats from the database. */ +export async function countAuthorStats( + store: SetRequired, + pubkey: string, +): Promise { + const [{ count: followers_count }, { count: notes_count }, [followList]] = await Promise.all([ + store.count([{ kinds: [3], '#p': [pubkey] }]), + store.count([{ kinds: [1], authors: [pubkey] }]), + store.query([{ kinds: [3], authors: [pubkey], limit: 1 }]), + ]); + + return { + pubkey, + followers_count, + following_count: getTagSet(followList?.tags ?? [], 'p').size, + notes_count, + }; +}