/ opencodehub / src / lib / activity.ts
Swadhin Biswas feat(api): add runner, analytics, packages, and security services · 3/6/2026
28f7954
46 lines · 1.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46

import { logger } from "@/lib/logger";
import { getDatabase, schema } from "@/db";
import { generateId } from "@/lib/utils";
import type { NodePgDatabase } from "drizzle-orm/node-postgres";

/**
 * Log a user activity to the database.
 * This is a fire-and-forget operation by default to avoid blocking the main request,
 * unless awaited explicitly.
 */
export async function logActivity(
    userId: string,
    type: string,
    action: string,
    targetType?: string,
    targetId?: string,
    repositoryId?: string,
    payload?: any,
    refType?: string,
    refName?: string,
    isPublic: boolean = true
) {
    try {
        const db = getDatabase() as NodePgDatabase<typeof schema>;

        await db.insert(schema.activities).values({
            id: generateId(),
            userId,
            repositoryId,
            type, // e.g. 'star', 'fork', 'push', 'issue', 'pr', 'follow'
            action, // e.g. 'created', 'opened', 'merged'
            targetType, // e.g. 'repository', 'issue', 'pull_request', 'user'
            targetId,
            refType,
            refName,
            payload: payload ? JSON.stringify(payload) : null,
            isPublic,
            createdAt: new Date(),
        });
    } catch (error) {
        logger.error("Failed to log activity:", error);
        // We don't throw here to avoid failing the main request
    }
}