summaryrefslogtreecommitdiff
path: root/app/api/tracking/page-duration/route.ts
blob: 861a52cc430b71eda7b8404acc650a99534f7655 (plain)
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
47
48
49
50
51
52
53
54
55
56
import { NextRequest, NextResponse } from 'next/server'
import { getServerSession } from 'next-auth'
import db from '@/db/db'
import { pageVisits } from '@/db/schema'
import { and, eq, desc, gte } from 'drizzle-orm'
import { authOptions } from '../../auth/[...nextauth]/route'

// 타입 변환 헬퍼
function ensureNumber(value: string | number): number {
    return typeof value === 'string' ? parseInt(value, 10) : value
  }
  
  export async function POST(request: NextRequest) {
    try {
      const session = await getServerSession(authOptions)
      const { route, duration, timestamp } = await request.json()
  
      // 세션이 있는 경우에만 체류 시간 업데이트
      if (session?.user?.id) {
        // string ID를 number로 변환
        const numericUserId = ensureNumber(session.user.id)
        
        // 최근 5분 내의 해당 라우트 방문 기록을 찾아서 체류 시간 업데이트
        const fiveMinutesAgo = new Date(Date.now() - 5 * 60 * 1000)
        
        // 방법 1: 서브쿼리를 사용해서 가장 최근 레코드의 ID를 찾아서 업데이트
        const latestVisitSubquery = db
          .select({ id: pageVisits.id })
          .from(pageVisits)
          .where(
            and(
              eq(pageVisits.userId, numericUserId),  // ✅ 이제 타입 매칭
              eq(pageVisits.route, route),
              gte(pageVisits.visitedAt, fiveMinutesAgo)
            )
          )
          .orderBy(desc(pageVisits.visitedAt))
          .limit(1)
  
        // 서브쿼리 결과를 사용해서 업데이트
        const latestVisit = await latestVisitSubquery
        
        if (latestVisit.length > 0) {
          await db
            .update(pageVisits)
            .set({ duration })
            .where(eq(pageVisits.id, latestVisit[0].id))
        }
      }
  
      return NextResponse.json({ success: true })
    } catch (error) {
      console.error('Page duration tracking API error:', error)
      return NextResponse.json({ success: false }, { status: 200 })
    }
  }