Skip to content

Commit 1f183ab

Browse files
committed
fix(cards): add card view tracking and view count analytics
1 parent 04658e3 commit 1f183ab

1 file changed

Lines changed: 29 additions & 1 deletion

File tree

apps/backend/src/routes/cards.ts

Lines changed: 29 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ import type { CardResponse } from '../services/cardService';
66
import type { Card } from '@devcard/shared';
77
import type { FastifyInstance, FastifyRequest, FastifyReply } from 'fastify';
88
import { CardVisibility } from '@prisma/client';
9-
import { request } from 'http';
9+
import { hashIp } from '../utils/refreshToken';
1010

1111
export interface CreateCardBody {
1212
title: string;
@@ -211,9 +211,37 @@ export async function cardRoutes(app: FastifyInstance): Promise<void> {
211211
//Get shared card
212212
app.get('/share/:slug', async(request: FastifyRequest<{Params: {slug: string}}>, reply: FastifyReply) => {
213213
const paramsSlug = request.params.slug;
214+
const userId = request.user.id
215+
const ip = hashIp(request.ip);
216+
const userAgent = request.headers['user-agent'] ?? 'unknown';
217+
214218

215219
try {
216220
const card = await cardService.getSharedCard(app, paramsSlug)
221+
222+
await app.prisma.$transaction([
223+
app.prisma.card.update({
224+
where: {
225+
id: card.id,
226+
},
227+
data: {
228+
viewCount: {
229+
increment: 1,
230+
},
231+
},
232+
}),
233+
234+
app.prisma.cardView.create({
235+
data: {
236+
cardId: card.id,
237+
ownerId: card.userId,
238+
viewerId: userId,
239+
source: 'link',
240+
viewerIp: ip,
241+
viewerAgent: userAgent,
242+
},
243+
}),
244+
]);
217245
return reply.status(200).send(card)
218246
} catch (error:any) {
219247
if (error?.code === 'CARD_NOT_FOUND') {

0 commit comments

Comments
 (0)