ai-wpa/app/api/topics/[slug]/view/route.ts

75 lines
1.8 KiB
TypeScript

import { NextRequest, NextResponse } from 'next/server'
import connectDB from '@/lib/mongodb'
import TopicModel from '@/models/topic'
// Track topic view (increment view count and daily analytics)
export async function POST(
request: NextRequest,
{ params }: { params: Promise<{ slug: string }> }
) {
try {
const { slug } = await params
if (!slug) {
return NextResponse.json(
{
success: false,
error: { message: 'Topic slug is required', code: 'MISSING_SLUG' },
},
{ status: 400 }
)
}
await connectDB()
// Get current date in YYYY-MM-DD format
const today = new Date().toISOString().split('T')[0]
// Find and update the topic
const topic = await TopicModel.findOneAndUpdate(
{ slug: slug, isDraft: false }, // Only track views for published posts
{
$inc: { views: 1 }, // Increment total views
$push: {
viewHistory: {
$each: [{ date: today, count: 1 }],
$slice: -30, // Keep only last 30 days
},
},
},
{
new: true,
projection: { views: 1, slug: 1, title: 1, authorId: 1 } // Include authorId for cache invalidation
}
)
if (!topic) {
return NextResponse.json(
{
success: false,
error: { message: 'Topic not found or is a draft', code: 'TOPIC_NOT_FOUND' },
},
{ status: 404 }
)
}
return NextResponse.json({
success: true,
data: {
slug: topic.slug,
title: topic.title,
views: topic.views,
},
})
} catch (error) {
console.error('View tracking error:', error)
return NextResponse.json(
{
success: false,
error: { message: 'Failed to track view', code: 'INTERNAL_ERROR' },
},
{ status: 500 }
)
}
}