Skip to content

Commit 47856c0

Browse files
authored
fix(analytics): use COUNT(DISTINCT viewer_id) for uniqueViewers instead of groupBy composite key (#449)
1 parent b029358 commit 47856c0

1 file changed

Lines changed: 8 additions & 7 deletions

File tree

apps/backend/src/routes/analytics.ts

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -70,13 +70,14 @@ export async function analyticsRoutes(
7070
// Count unique viewers
7171
// In raw SQL this is `SELECT COUNT(DISTINCT viewer_id) FROM card_views WHERE owner_id = ?`
7272
// Prisma group-by as workaround:
73-
const uniqueViewersQuery =
74-
await app.prisma.cardView.groupBy({
75-
by: ['viewerId', 'viewerIp'],
76-
where: { ownerId: userId },
77-
});
78-
79-
const uniqueViewers = uniqueViewersQuery.length;
73+
const uniqueViewersQuery = await app.prisma.$queryRaw<[{ count: bigint }]>`
74+
SELECT COUNT(DISTINCT viewer_id) AS count
75+
FROM card_views
76+
WHERE owner_id = ${userId}
77+
AND viewer_id IS NOT NULL
78+
`;
79+
80+
const uniqueViewers = Number(uniqueViewersQuery[0]?.count ?? 0);
8081

8182
return {
8283
totalViews,

0 commit comments

Comments
 (0)