|
| 1 | +import { NextRequest, NextResponse } from 'next/server'; |
| 2 | +import { cookies } from 'next/headers'; |
| 3 | +import { auth } from '@/lib/auth'; |
| 4 | +import { checkDatabaseAvailability } from '@/lib/utils/database-check'; |
| 5 | +import { isBot } from '@/lib/utils/bot-detection'; |
| 6 | +import { recordItemView } from '@/lib/db/queries/item-view.queries'; |
| 7 | +import { ItemRepository } from '@/lib/repositories/item.repository'; |
| 8 | +import { VIEWER_COOKIE_NAME, VIEWER_COOKIE_MAX_AGE } from '@/lib/constants/analytics'; |
| 9 | + |
| 10 | +type RouteParams = { params: Promise<{ slug: string }> }; |
| 11 | + |
| 12 | +/** |
| 13 | + * POST /api/items/[slug]/views |
| 14 | + * |
| 15 | + * Records a unique daily view for an item. |
| 16 | + * |
| 17 | + * Flow: |
| 18 | + * 1. Check database availability |
| 19 | + * 2. Detect and reject bots |
| 20 | + * 3. Exclude owner views (if authenticated) |
| 21 | + * 4. Get or create viewer ID from cookie |
| 22 | + * 5. Record view with daily deduplication |
| 23 | + * |
| 24 | + * Response: |
| 25 | + * - { success: true, counted: true } - New view recorded |
| 26 | + * - { success: true, counted: false } - Duplicate view (same day) |
| 27 | + * - { success: true, counted: false, reason: "bot" } - Bot detected |
| 28 | + * - { success: true, counted: false, reason: "owner" } - Owner viewing own item |
| 29 | + */ |
| 30 | +export async function POST(request: NextRequest, { params }: RouteParams) { |
| 31 | + try { |
| 32 | + // 1. Database availability check |
| 33 | + const dbCheck = checkDatabaseAvailability(); |
| 34 | + if (dbCheck) return dbCheck; |
| 35 | + |
| 36 | + const { slug } = await params; |
| 37 | + |
| 38 | + // 2. Bot detection |
| 39 | + const userAgent = request.headers.get('user-agent') || ''; |
| 40 | + if (isBot(userAgent)) { |
| 41 | + return NextResponse.json({ success: true, counted: false, reason: 'bot' }); |
| 42 | + } |
| 43 | + |
| 44 | + // 3. Owner exclusion (if authenticated) - check before cookie handling |
| 45 | + const session = await auth(); |
| 46 | + if (session?.user?.id) { |
| 47 | + const itemRepository = new ItemRepository(); |
| 48 | + const item = await itemRepository.findBySlug(slug); |
| 49 | + if (item?.submitted_by === session.user.id) { |
| 50 | + return NextResponse.json({ success: true, counted: false, reason: 'owner' }); |
| 51 | + } |
| 52 | + } |
| 53 | + |
| 54 | + // 4. Get or create viewer ID from cookie |
| 55 | + const cookieStore = await cookies(); |
| 56 | + let viewerId = cookieStore.get(VIEWER_COOKIE_NAME)?.value; |
| 57 | + const isNewViewer = !viewerId; |
| 58 | + |
| 59 | + if (!viewerId) { |
| 60 | + viewerId = crypto.randomUUID(); |
| 61 | + } |
| 62 | + |
| 63 | + // 5. Record view with daily deduplication |
| 64 | + const viewedDateUtc = new Date().toISOString().split('T')[0]; // YYYY-MM-DD |
| 65 | + const counted = await recordItemView({ |
| 66 | + itemId: slug, |
| 67 | + viewerId, |
| 68 | + viewedDateUtc |
| 69 | + }); |
| 70 | + |
| 71 | + // 6. Set cookie if new viewer |
| 72 | + if (isNewViewer) { |
| 73 | + cookieStore.set(VIEWER_COOKIE_NAME, viewerId, { |
| 74 | + httpOnly: true, |
| 75 | + secure: process.env.NODE_ENV === 'production', |
| 76 | + sameSite: 'lax', |
| 77 | + maxAge: VIEWER_COOKIE_MAX_AGE, |
| 78 | + path: '/' |
| 79 | + }); |
| 80 | + } |
| 81 | + |
| 82 | + return NextResponse.json({ success: true, counted }); |
| 83 | + } catch (error) { |
| 84 | + if (process.env.NODE_ENV === 'development') { |
| 85 | + console.error('Error recording item view:', error); |
| 86 | + } |
| 87 | + return NextResponse.json({ success: false, error: 'Failed to record view' }, { status: 500 }); |
| 88 | + } |
| 89 | +} |
0 commit comments