Files
la-huasca-ts/src/app/api/rooms/[id]/likes/route.ts
T

55 lines
1.9 KiB
TypeScript

import { NextRequest, NextResponse } from 'next/server';
import { db } from '@/lib/db';
export async function GET(request: NextRequest, { params }: { params: { id: string } }) {
try {
const roomId = parseInt(params.id, 10);
if (isNaN(roomId)) {
return NextResponse.json({ error: 'Invalid room ID' }, { status: 400 });
}
const [countResult, userLikeResult] = await Promise.all([
db.query('SELECT COUNT(*) AS count FROM room_likes WHERE room_id = $1', [roomId]),
db.query('SELECT 1 FROM room_likes WHERE room_id = $1 AND user_id = $2', [roomId, 1]),
]);
return NextResponse.json({
count: parseInt(countResult.rows[0].count, 10),
user_liked: userLikeResult.rows.length > 0,
});
} catch (err: any) {
// Table may not exist yet — return safe defaults
return NextResponse.json({ count: 0, user_liked: false });
}
}
export async function POST(request: NextRequest, { params }: { params: { id: string } }) {
try {
const roomId = parseInt(params.id, 10);
if (isNaN(roomId)) {
return NextResponse.json({ error: 'Invalid room ID' }, { status: 400 });
}
// TODO: get user_id from session/auth instead of hardcoded
const userId = 1;
// Toggle: if already liked, unlike; otherwise like
const existing = await db.query(
'SELECT id FROM room_likes WHERE room_id = $1 AND user_id = $2',
[roomId, userId]
);
if (existing.rows.length > 0) {
await db.query('DELETE FROM room_likes WHERE id = $1', [existing.rows[0].id]);
} else {
await db.query('INSERT INTO room_likes (room_id, user_id) VALUES ($1, $2)', [roomId, userId]);
}
const countResult = await db.query('SELECT COUNT(*) AS count FROM room_likes WHERE room_id = $1', [roomId]);
return NextResponse.json({ count: parseInt(countResult.rows[0].count, 10) });
} catch (err: any) {
return NextResponse.json({ error: err.message || 'Failed to toggle like' }, { status: 500 });
}
}