chatbot-template/app/(chat)/api/vote/route.ts

76 lines
1.7 KiB
TypeScript
Raw Normal View History

import { auth } from "@/app/(auth)/auth";
import { getChatById, getVotesByChatId, voteMessage } from "@/lib/db/queries";
import { OpenChatError } 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");
2024-11-05 17:15:51 +03:00
if (!chatId) {
return new OpenChatError(
"bad_request:api",
"Parameter chatId is required."
2025-05-13 19:01:28 -07:00
).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 OpenChatError("unauthorized:vote").toResponse();
2024-11-05 17:15:51 +03:00
}
const chat = await getChatById({ id: chatId });
if (!chat) {
return new OpenChatError("not_found:chat").toResponse();
}
if (chat.userId !== session.user.id) {
return new OpenChatError("forbidden:vote").toResponse();
}
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" } =
2024-11-05 17:15:51 +03:00
await request.json();
if (!chatId || !messageId || !type) {
return new OpenChatError(
"bad_request:api",
"Parameters chatId, messageId, and type are required."
2025-05-13 19:01:28 -07:00
).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 OpenChatError("unauthorized:vote").toResponse();
2024-11-05 17:15:51 +03:00
}
const chat = await getChatById({ id: chatId });
if (!chat) {
return new OpenChatError("not_found:vote").toResponse();
}
if (chat.userId !== session.user.id) {
return new OpenChatError("forbidden:vote").toResponse();
}
2024-11-05 17:15:51 +03:00
await voteMessage({
chatId,
messageId,
type,
2024-11-05 17:15:51 +03:00
});
return new Response("Message voted", { status: 200 });
2024-11-05 17:15:51 +03:00
}