initial commit
This commit is contained in:
71
app/api/topics/[slug]/related/route.ts
Normal file
71
app/api/topics/[slug]/related/route.ts
Normal file
@@ -0,0 +1,71 @@
|
||||
import { NextRequest, NextResponse } from 'next/server'
|
||||
import connectDB from '@/lib/mongodb'
|
||||
import TopicModel, { transformToTopics } from '@/models/topic'
|
||||
|
||||
export async function GET(
|
||||
request: NextRequest,
|
||||
{ params }: { params: Promise<{ slug: string }> }
|
||||
) {
|
||||
try {
|
||||
await connectDB()
|
||||
|
||||
const { slug } = await params
|
||||
const searchParams = request.nextUrl.searchParams
|
||||
const limit = parseInt(searchParams.get('limit') || '2')
|
||||
|
||||
if (!slug) {
|
||||
return NextResponse.json(
|
||||
{
|
||||
success: false,
|
||||
error: {
|
||||
message: 'Topic slug is required',
|
||||
code: 'SLUG_REQUIRED',
|
||||
},
|
||||
},
|
||||
{ status: 400 }
|
||||
)
|
||||
}
|
||||
|
||||
// First, get the current post to find its ID and tags
|
||||
const currentPost = await TopicModel.findOne({
|
||||
slug,
|
||||
isDraft: false
|
||||
}).lean()
|
||||
|
||||
if (!currentPost) {
|
||||
return NextResponse.json({
|
||||
success: true,
|
||||
data: [],
|
||||
})
|
||||
}
|
||||
|
||||
// Find related posts by excluding the current post and sorting by publishedAt
|
||||
const relatedPosts = await TopicModel.find({
|
||||
id: { $ne: currentPost.id },
|
||||
isDraft: false,
|
||||
})
|
||||
.sort({ publishedAt: -1 })
|
||||
.limit(limit)
|
||||
.lean()
|
||||
|
||||
// Transform to proper format
|
||||
const transformedPosts = transformToTopics(relatedPosts)
|
||||
|
||||
return NextResponse.json({
|
||||
success: true,
|
||||
data: transformedPosts,
|
||||
})
|
||||
} catch (error) {
|
||||
console.error('Error fetching related posts:', error)
|
||||
return NextResponse.json(
|
||||
{
|
||||
success: false,
|
||||
error: {
|
||||
message: 'Failed to fetch related posts',
|
||||
code: 'SERVER_ERROR',
|
||||
},
|
||||
},
|
||||
{ status: 500 }
|
||||
)
|
||||
}
|
||||
}
|
||||
79
app/api/topics/[slug]/route.ts
Normal file
79
app/api/topics/[slug]/route.ts
Normal file
@@ -0,0 +1,79 @@
|
||||
import { NextRequest, NextResponse } from 'next/server'
|
||||
import connectDB from '@/lib/mongodb'
|
||||
import TopicModel, { transformToTopic } from '@/models/topic'
|
||||
|
||||
export async function GET(
|
||||
request: NextRequest,
|
||||
{ params }: { params: Promise<{ slug: string }> }
|
||||
) {
|
||||
try {
|
||||
await connectDB()
|
||||
|
||||
const { slug } = await params
|
||||
|
||||
if (!slug) {
|
||||
return NextResponse.json(
|
||||
{
|
||||
success: false,
|
||||
error: {
|
||||
message: 'Topic slug is required',
|
||||
code: 'SLUG_REQUIRED',
|
||||
},
|
||||
},
|
||||
{ status: 400 }
|
||||
)
|
||||
}
|
||||
|
||||
// Find the topic post by slug (only published posts)
|
||||
const post = await TopicModel.findOne({
|
||||
slug,
|
||||
isDraft: false
|
||||
}).lean()
|
||||
|
||||
if (!post) {
|
||||
return NextResponse.json(
|
||||
{
|
||||
success: false,
|
||||
error: {
|
||||
message: 'Topic post not found',
|
||||
code: 'POST_NOT_FOUND',
|
||||
},
|
||||
},
|
||||
{ status: 404 }
|
||||
)
|
||||
}
|
||||
|
||||
// Transform to proper format
|
||||
const transformedPost = transformToTopic(post)
|
||||
|
||||
if (!transformedPost) {
|
||||
return NextResponse.json(
|
||||
{
|
||||
success: false,
|
||||
error: {
|
||||
message: 'Failed to process topic post',
|
||||
code: 'PROCESSING_ERROR',
|
||||
},
|
||||
},
|
||||
{ status: 500 }
|
||||
)
|
||||
}
|
||||
|
||||
return NextResponse.json({
|
||||
success: true,
|
||||
data: transformedPost,
|
||||
})
|
||||
} catch (error) {
|
||||
console.error('Error fetching topic post:', error)
|
||||
return NextResponse.json(
|
||||
{
|
||||
success: false,
|
||||
error: {
|
||||
message: 'Failed to fetch topic post',
|
||||
code: 'SERVER_ERROR',
|
||||
},
|
||||
},
|
||||
{ status: 500 }
|
||||
)
|
||||
}
|
||||
}
|
||||
75
app/api/topics/[slug]/view/route.ts
Normal file
75
app/api/topics/[slug]/view/route.ts
Normal file
@@ -0,0 +1,75 @@
|
||||
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 }
|
||||
)
|
||||
}
|
||||
}
|
||||
142
app/api/topics/route.ts
Normal file
142
app/api/topics/route.ts
Normal file
@@ -0,0 +1,142 @@
|
||||
import { NextRequest, NextResponse } from 'next/server'
|
||||
import connectDB from '@/lib/mongodb'
|
||||
import TopicModel, { transformToTopics } from '@/models/topic'
|
||||
import { authMiddleware } from '@/lib/auth-middleware'
|
||||
import { ZodError } from 'zod'
|
||||
|
||||
export async function GET(request: NextRequest) {
|
||||
try {
|
||||
await connectDB()
|
||||
const searchParams = request.nextUrl.searchParams
|
||||
const page = parseInt(searchParams.get('page') || '1')
|
||||
const limit = parseInt(searchParams.get('limit') || '10')
|
||||
const search = searchParams.get('q') || ''
|
||||
const tag = searchParams.get('tag') || ''
|
||||
const authorId = searchParams.get('authorId') || '' // For filtering by user's topics
|
||||
const includeDrafts = searchParams.get('includeDrafts') === 'true' // For user's own topics
|
||||
const fetchAll = searchParams.get('fetchAll') // Admin panel support
|
||||
const skip = (page - 1) * limit
|
||||
|
||||
// Build query based on parameters
|
||||
const query: any = {}
|
||||
|
||||
// Authentication check for private operations (drafts or admin)
|
||||
let user = null
|
||||
try {
|
||||
user = await authMiddleware(request)
|
||||
} catch (error) {
|
||||
// Non-authenticated request - that's okay for public topic listing
|
||||
}
|
||||
|
||||
// If requesting user's own topics with drafts, verify authentication
|
||||
if (includeDrafts && !user) {
|
||||
return NextResponse.json(
|
||||
{
|
||||
success: false,
|
||||
error: { message: 'Authentication required to view drafts', code: 'AUTH_REQUIRED' },
|
||||
},
|
||||
{ status: 401 }
|
||||
)
|
||||
}
|
||||
|
||||
// Filter by author if specified
|
||||
if (authorId) {
|
||||
query.authorId = authorId
|
||||
}
|
||||
|
||||
// Handle draft filtering
|
||||
if (fetchAll === 'true') {
|
||||
// Admin panel - show all posts (drafts and published)
|
||||
// No draft filtering applied
|
||||
} else if (includeDrafts && user && (authorId === user.id || !authorId)) {
|
||||
// User requesting their own topics (including drafts)
|
||||
if (!authorId) {
|
||||
query.authorId = user.id
|
||||
}
|
||||
} else {
|
||||
// Public topic listing - only published topics
|
||||
query.isDraft = false
|
||||
}
|
||||
|
||||
// Search functionality
|
||||
if (search) {
|
||||
query.$or = [
|
||||
{ title: { $regex: search, $options: 'i' } },
|
||||
{ excerpt: { $regex: search, $options: 'i' } },
|
||||
{ content: { $regex: search, $options: 'i' } },
|
||||
]
|
||||
}
|
||||
|
||||
// Filter by tag
|
||||
if (tag) {
|
||||
query['tags.name'] = { $regex: new RegExp(tag, 'i') }
|
||||
}
|
||||
|
||||
// Get total count with same filters
|
||||
const totalTopics = await TopicModel.countDocuments(query)
|
||||
|
||||
// Get paginated topics sorted by publishedAt
|
||||
const topics = await TopicModel.find(query)
|
||||
.sort({ publishedAt: -1 })
|
||||
.skip(skip)
|
||||
.limit(limit)
|
||||
.lean()
|
||||
|
||||
if (!topics || topics.length === 0) {
|
||||
return NextResponse.json(
|
||||
{
|
||||
success: true,
|
||||
data: [],
|
||||
pagination: {
|
||||
total: 0,
|
||||
page,
|
||||
limit,
|
||||
totalPages: 0,
|
||||
},
|
||||
},
|
||||
{ status: 200 }
|
||||
)
|
||||
}
|
||||
|
||||
// Transform the topics using our utility function
|
||||
const transformedTopics = transformToTopics(topics)
|
||||
|
||||
return NextResponse.json(
|
||||
{
|
||||
success: true,
|
||||
data: transformedTopics,
|
||||
pagination: {
|
||||
total: totalTopics,
|
||||
page,
|
||||
limit,
|
||||
totalPages: Math.ceil(totalTopics / limit),
|
||||
},
|
||||
},
|
||||
{ status: 200 }
|
||||
)
|
||||
} catch (error) {
|
||||
console.error('Error fetching topics:', error)
|
||||
|
||||
if (error instanceof ZodError) {
|
||||
return NextResponse.json(
|
||||
{
|
||||
success: false,
|
||||
error: {
|
||||
message: 'Data validation failed',
|
||||
code: 'VALIDATION_ERROR',
|
||||
details: error.issues,
|
||||
},
|
||||
},
|
||||
{ status: 400 }
|
||||
)
|
||||
}
|
||||
|
||||
return NextResponse.json(
|
||||
{
|
||||
success: false,
|
||||
error: { message: 'Failed to fetch topics', code: 'SERVER_ERROR' },
|
||||
},
|
||||
{ status: 500 }
|
||||
)
|
||||
}
|
||||
}
|
||||
39
app/api/topics/tags/route.ts
Normal file
39
app/api/topics/tags/route.ts
Normal file
@@ -0,0 +1,39 @@
|
||||
import { NextRequest, NextResponse } from 'next/server'
|
||||
import connectDB from '@/lib/mongodb'
|
||||
import TopicModel from '@/models/topic'
|
||||
|
||||
export async function GET(request: NextRequest) {
|
||||
try {
|
||||
await connectDB()
|
||||
|
||||
// Get all unique tags from published topics
|
||||
const topics = await TopicModel.find({ isDraft: false }).select('tags').lean()
|
||||
const tags = new Set<string>()
|
||||
|
||||
topics.forEach((topic) => {
|
||||
topic.tags.forEach((tag: { id?: string; name: string }) => tags.add(tag.name))
|
||||
})
|
||||
|
||||
const uniqueTags = Array.from(tags).map((name, index) => ({
|
||||
id: String(index + 1),
|
||||
name
|
||||
}))
|
||||
|
||||
return NextResponse.json({
|
||||
success: true,
|
||||
data: uniqueTags,
|
||||
})
|
||||
} catch (error) {
|
||||
console.error('Error fetching tags:', error)
|
||||
return NextResponse.json(
|
||||
{
|
||||
success: false,
|
||||
error: {
|
||||
message: 'Failed to fetch tags',
|
||||
code: 'TAGS_FETCH_ERROR',
|
||||
},
|
||||
},
|
||||
{ status: 500 }
|
||||
)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user