chatbot-template/app/(chat)/chat/[id]/page.tsx

82 lines
2 KiB
TypeScript
Raw Normal View History

import { cookies } from "next/headers";
import { notFound, redirect } from "next/navigation";
2025-11-29 13:21:34 +00:00
import { Suspense } from "react";
import { Chat } from "@/components/chat";
import { DataStreamHandler } from "@/components/data-stream-handler";
import { DEFAULT_CHAT_MODEL } from "@/lib/ai/models";
import { getSession } from "@/lib/auth";
import { getChatById, getMessagesByChatId } from "@/lib/db/queries";
import { convertToUIMessages } from "@/lib/utils";
2024-10-11 18:00:22 +05:30
2025-11-29 13:21:34 +00:00
export default function Page(props: { params: Promise<{ id: string }> }) {
return (
<Suspense fallback={<div className="flex h-dvh" />}>
<ChatPage params={props.params} />
</Suspense>
);
}
async function ChatPage({ params }: { params: Promise<{ id: string }> }) {
const { id } = await params;
2024-11-05 17:15:51 +03:00
const chat = await getChatById({ id });
2024-10-11 18:00:22 +05:30
2024-11-05 17:15:51 +03:00
if (!chat) {
redirect("/");
2023-06-16 21:52:01 +04:00
}
const session = await getSession();
2024-10-11 18:00:22 +05:30
2025-04-25 23:40:15 -07:00
if (!session) {
redirect("/login");
2025-04-25 23:40:15 -07:00
}
if (chat.visibility === "private") {
2025-04-25 23:40:15 -07:00
if (!session.user) {
return notFound();
}
if (session.user.id !== chat.userId) {
return notFound();
}
2023-06-16 15:28:43 -04:00
}
2024-10-11 18:00:22 +05:30
2024-11-05 17:15:51 +03:00
const messagesFromDb = await getMessagesByChatId({
id,
});
const uiMessages = convertToUIMessages(messagesFromDb);
const cookieStore = await cookies();
const chatModelFromCookie = cookieStore.get("chat-model");
if (!chatModelFromCookie) {
return (
<>
<Chat
autoResume={true}
id={chat.id}
initialChatModel={DEFAULT_CHAT_MODEL}
initialMessages={uiMessages}
initialVisibilityType={chat.visibility}
isReadonly={session?.user?.id !== chat.userId}
/>
<DataStreamHandler />
</>
);
}
return (
2024-12-20 23:07:23 +05:30
<>
<Chat
autoResume={true}
2024-12-20 23:07:23 +05:30
id={chat.id}
initialChatModel={chatModelFromCookie.value}
initialMessages={uiMessages}
initialVisibilityType={chat.visibility}
2024-12-20 23:07:23 +05:30
isReadonly={session?.user?.id !== chat.userId}
/>
<DataStreamHandler />
2024-12-20 23:07:23 +05:30
</>
);
2023-06-02 15:15:35 -04:00
}