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

89 lines
2.3 KiB
TypeScript
Raw Normal View History

import { cookies } from 'next/headers';
2025-04-25 23:40:15 -07:00
import { notFound, redirect } from 'next/navigation';
2023-05-19 12:33:56 -04:00
import { auth } from '@/app/(auth)/auth';
2024-11-30 16:44:40 -05:00
import { Chat } from '@/components/chat';
2024-11-15 10:13:21 -05:00
import { getChatById, getMessagesByChatId } from '@/lib/db/queries';
2024-12-20 23:07:23 +05:30
import { DataStreamHandler } from '@/components/data-stream-handler';
import { DEFAULT_CHAT_MODEL } from '@/lib/ai/models';
2025-04-25 23:40:15 -07:00
import type { DBMessage } from '@/lib/db/schema';
import type { Attachment, UIMessage } from 'ai';
2024-10-11 18:00:22 +05:30
2024-11-15 12:18:17 -05:00
export default async function Page(props: { params: Promise<{ id: string }> }) {
2024-10-23 12:21:30 -04:00
const params = await props.params;
2024-10-11 18:00:22 +05:30
const { id } = 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) {
2024-10-11 18:00:22 +05:30
notFound();
2023-06-16 21:52:01 +04:00
}
2024-10-11 18:00:22 +05:30
const session = await auth();
2025-04-25 23:40:15 -07:00
if (!session) {
redirect('/api/auth/guest');
}
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,
});
function convertToUIMessages(messages: Array<DBMessage>): Array<UIMessage> {
return messages.map((message) => ({
id: message.id,
parts: message.parts as UIMessage['parts'],
role: message.role as UIMessage['role'],
// Note: content will soon be deprecated in @ai-sdk/react
content: '',
createdAt: message.createdAt,
experimental_attachments:
(message.attachments as Array<Attachment>) ?? [],
}));
}
const cookieStore = await cookies();
const chatModelFromCookie = cookieStore.get('chat-model');
if (!chatModelFromCookie) {
return (
<>
<Chat
id={chat.id}
initialMessages={convertToUIMessages(messagesFromDb)}
initialChatModel={DEFAULT_CHAT_MODEL}
initialVisibilityType={chat.visibility}
isReadonly={session?.user?.id !== chat.userId}
2025-04-25 23:40:15 -07:00
session={session}
autoResume={true}
/>
<DataStreamHandler id={id} />
</>
);
}
return (
2024-12-20 23:07:23 +05:30
<>
<Chat
id={chat.id}
initialMessages={convertToUIMessages(messagesFromDb)}
initialChatModel={chatModelFromCookie.value}
initialVisibilityType={chat.visibility}
2024-12-20 23:07:23 +05:30
isReadonly={session?.user?.id !== chat.userId}
2025-04-25 23:40:15 -07:00
session={session}
autoResume={true}
2024-12-20 23:07:23 +05:30
/>
<DataStreamHandler id={id} />
</>
);
2023-06-02 15:15:35 -04:00
}