49 lines
1.5 KiB
TypeScript
49 lines
1.5 KiB
TypeScript
import { NextResponse } from 'next/server';
|
|
import { getDb } from '@/lib/db';
|
|
import { polls } from '@/lib/db/schema';
|
|
import { eq } from 'drizzle-orm';
|
|
|
|
export async function GET(request: Request) {
|
|
try {
|
|
const { searchParams } = new URL(request.url);
|
|
const id = searchParams.get('id');
|
|
const db = getDb(process.env.DATABASE_URL!);
|
|
|
|
if (id) {
|
|
const poll = await db.query.polls.findFirst({
|
|
where: eq(polls.id, id),
|
|
with: {
|
|
options: {
|
|
orderBy: (options, { asc }) => [asc(options.position)],
|
|
},
|
|
},
|
|
});
|
|
|
|
if (!poll) {
|
|
return NextResponse.json({ message: 'Poll not found' }, { status: 404 });
|
|
}
|
|
return NextResponse.json(poll);
|
|
}
|
|
|
|
// Fetch the most recent active poll
|
|
const activePoll = await db.query.polls.findFirst({
|
|
where: eq(polls.status, 'active'),
|
|
orderBy: (polls, { desc }) => [desc(polls.createdAt)],
|
|
with: {
|
|
options: {
|
|
orderBy: (options, { asc }) => [asc(options.position)],
|
|
},
|
|
},
|
|
});
|
|
|
|
if (!activePoll) {
|
|
return NextResponse.json({ message: 'No active poll found' }, { status: 404 });
|
|
}
|
|
|
|
return NextResponse.json(activePoll);
|
|
} catch (e) {
|
|
console.error('Error fetching poll:', e);
|
|
return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
|
|
}
|
|
}
|