2024-11-05 17:15:51 +03:00
|
|
|
import { auth } from '@/app/(auth)/auth';
|
2025-03-05 10:03:17 -08:00
|
|
|
import { getChatById, getVotesByChatId, voteMessage } from '@/lib/db/queries';
|
2025-05-13 19:01:28 -07:00
|
|
|
import { ChatSDKError } from '@/lib/errors';
|
2024-11-05 17:15:51 +03:00
|
|
|
|
|
|
|
|
export async function GET(request: Request) {
|
|
|
|
|
const { searchParams } = new URL(request.url);
|
|
|
|
|
const chatId = searchParams.get('chatId');
|
|
|
|
|
|
|
|
|
|
if (!chatId) {
|
2025-05-13 19:01:28 -07:00
|
|
|
return new ChatSDKError(
|
|
|
|
|
'bad_request:api',
|
|
|
|
|
'Parameter chatId is required.',
|
|
|
|
|
).toResponse();
|
2024-11-05 17:15:51 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
const session = await auth();
|
|
|
|
|
|
2025-05-13 19:01:28 -07:00
|
|
|
if (!session?.user) {
|
|
|
|
|
return new ChatSDKError('unauthorized:vote').toResponse();
|
2024-11-05 17:15:51 +03:00
|
|
|
}
|
|
|
|
|
|
2025-03-05 10:03:17 -08:00
|
|
|
const chat = await getChatById({ id: chatId });
|
|
|
|
|
|
|
|
|
|
if (!chat) {
|
2025-05-13 19:01:28 -07:00
|
|
|
return new ChatSDKError('not_found:chat').toResponse();
|
2025-03-05 10:03:17 -08:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if (chat.userId !== session.user.id) {
|
2025-05-13 19:01:28 -07:00
|
|
|
return new ChatSDKError('forbidden:vote').toResponse();
|
2025-03-05 10:03:17 -08:00
|
|
|
}
|
|
|
|
|
|
2024-11-05 17:15:51 +03:00
|
|
|
const votes = await getVotesByChatId({ id: chatId });
|
|
|
|
|
|
|
|
|
|
return Response.json(votes, { status: 200 });
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
export async function PATCH(request: Request) {
|
|
|
|
|
const {
|
|
|
|
|
chatId,
|
|
|
|
|
messageId,
|
|
|
|
|
type,
|
|
|
|
|
}: { chatId: string; messageId: string; type: 'up' | 'down' } =
|
|
|
|
|
await request.json();
|
|
|
|
|
|
|
|
|
|
if (!chatId || !messageId || !type) {
|
2025-05-13 19:01:28 -07:00
|
|
|
return new ChatSDKError(
|
|
|
|
|
'bad_request:api',
|
|
|
|
|
'Parameters chatId, messageId, and type are required.',
|
|
|
|
|
).toResponse();
|
2024-11-05 17:15:51 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
const session = await auth();
|
|
|
|
|
|
2025-05-13 19:01:28 -07:00
|
|
|
if (!session?.user) {
|
|
|
|
|
return new ChatSDKError('unauthorized:vote').toResponse();
|
2024-11-05 17:15:51 +03:00
|
|
|
}
|
|
|
|
|
|
2025-03-05 10:03:17 -08:00
|
|
|
const chat = await getChatById({ id: chatId });
|
|
|
|
|
|
|
|
|
|
if (!chat) {
|
2025-05-13 19:01:28 -07:00
|
|
|
return new ChatSDKError('not_found:vote').toResponse();
|
2025-03-05 10:03:17 -08:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if (chat.userId !== session.user.id) {
|
2025-05-13 19:01:28 -07:00
|
|
|
return new ChatSDKError('forbidden:vote').toResponse();
|
2025-03-05 10:03:17 -08:00
|
|
|
}
|
|
|
|
|
|
2024-11-05 17:15:51 +03:00
|
|
|
await voteMessage({
|
|
|
|
|
chatId,
|
|
|
|
|
messageId,
|
|
|
|
|
type: type,
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
return new Response('Message voted', { status: 200 });
|
|
|
|
|
}
|