2025-12-08 16:31:30 +03:00

78 lines
2.3 KiB
TypeScript

import { NextRequest, NextResponse } from 'next/server'
import { redis } from '@/lib/redis'
export async function GET(req: NextRequest, { params }: { params: { id: string } }) {
try {
const { id: pollId } = params
const commentsData = await redis.lrange(`comments:${pollId}`, 0, -1)
const comments = commentsData.map(c => JSON.parse(c))
const buildTree = (parentId: string | null = null, level: number = 0): any[] => {
return comments
.filter(c => c.parentId === parentId)
.map(c => ({
...c,
level,
replies: level < 3 ? buildTree(c.id, level + 1) : []
}))
.sort((a, b) => b.timestamp - a.timestamp)
}
const tree = buildTree()
return NextResponse.json({ comments: tree })
} catch (error) {
console.error('Comments GET error:', error)
return NextResponse.json({ comments: [] })
}
}
export async function POST(req: NextRequest, { params }: { params: { id: string } }) {
try {
const { id: pollId } = params
const { text, parentId, authorFid, authorUsername, authorPfp } = await req.json()
if (!authorFid || !authorUsername) {
return NextResponse.json({ error: 'Author information required' }, { status: 400 })
}
const comment = {
id: `comment-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`,
pollId,
authorFid,
authorUsername,
authorPfp,
text,
timestamp: Date.now(),
likes: 0,
liked: false,
parentId: parentId || null
}
await redis.lpush(`comments:${pollId}`, JSON.stringify(comment))
const mentions = text.match(/@(\w+)/g)
if (mentions) {
for (const mention of mentions) {
const username = mention.slice(1)
const notification = {
id: `mention-${comment.id}`,
type: 'mention',
fromFid: authorFid,
pollId,
commentId: comment.id,
timestamp: Date.now(),
read: false
}
await redis.lpush(`notifications:mention:${username}`, JSON.stringify(notification))
}
}
return NextResponse.json({ success: true, comment })
} catch (error) {
console.error('Comments POST error:', error)
return NextResponse.json({ error: 'Failed to post comment' }, { status: 500 })
}
}