stats: add (and test) countAuthorStats

This commit is contained in:
Alex Gleason 2024-05-24 16:24:47 -05:00
parent 34f3cc8d24
commit ee2065b76b
No known key found for this signature in database
GPG Key ID: 7211D1F99744FBB7
2 changed files with 37 additions and 1 deletions

View File

@ -2,7 +2,7 @@ import { assertEquals } from '@std/assert';
import { generateSecretKey, getPublicKey } from 'nostr-tools'; import { generateSecretKey, getPublicKey } from 'nostr-tools';
import { genEvent, getTestDB } from '@/test.ts'; 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 () => { Deno.test('updateStats with kind 1 increments notes count', async () => {
await using db = await getTestDB(); await using db = await getTestDB();
@ -142,3 +142,19 @@ Deno.test('updateStats with kind 5 decrements reactions count', async () => {
assertEquals(stats!.reactions_count, 0); 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);
});

View File

@ -1,5 +1,6 @@
import { NostrEvent, NStore } from '@nostrify/nostrify'; import { NostrEvent, NStore } from '@nostrify/nostrify';
import { Kysely, UpdateObject } from 'kysely'; import { Kysely, UpdateObject } from 'kysely';
import { SetRequired } from 'type-fest';
import { DittoTables } from '@/db/DittoTables.ts'; import { DittoTables } from '@/db/DittoTables.ts';
import { getTagSet } from '@/utils/tags.ts'; import { getTagSet } from '@/utils/tags.ts';
@ -176,3 +177,22 @@ export async function updateEventStats(
.execute(); .execute();
} }
} }
/** Calculate author stats from the database. */
export async function countAuthorStats(
store: SetRequired<NStore, 'count'>,
pubkey: string,
): Promise<DittoTables['author_stats']> {
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,
};
}