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

50 lines
1.4 KiB
TypeScript

import { NextRequest, NextResponse } from 'next/server'
import { getAllPolls } from '@/lib/polls'
export async function GET(req: NextRequest) {
try {
const { searchParams } = new URL(req.url)
const search = searchParams.get('search')?.toLowerCase() || ''
const status = searchParams.get('status') || 'all'
const category = searchParams.get('category') || 'all'
const sort = searchParams.get('sort') || 'newest'
let polls = await getAllPolls()
if (search) {
polls = polls.filter(poll =>
poll.question.toLowerCase().includes(search) ||
poll.description?.toLowerCase().includes(search)
)
}
if (status !== 'all') {
polls = polls.filter(p => p.status === status)
}
if (category !== 'all') {
polls = polls.filter(p => p.category === category)
}
switch (sort) {
case 'newest':
polls.sort((a, b) => b.createdAt - a.createdAt)
break
case 'popular':
polls.sort((a, b) => b.totalVotes - a.totalVotes)
break
case 'ending':
polls.sort((a, b) => (a.endsAt || Infinity) - (b.endsAt || Infinity))
break
case 'pot':
polls.sort((a, b) => b.totalAmount - a.totalAmount)
break
}
return NextResponse.json({ polls })
} catch (error) {
console.error('Discover API error:', error)
return NextResponse.json({ polls: [] })
}
}