|
| 1 | +import type { Metadata } from "next"; |
| 2 | +import { notFound, redirect } from "next/navigation"; |
| 3 | + |
| 4 | +import { Chat } from "~/components/ai/chat"; |
| 5 | +import { AI, getChat } from "~/components/ai/chat/actions"; |
| 6 | +import type { Session } from "~/utils/types"; |
| 7 | +import { createClient } from "~/supabase/server"; |
| 8 | + |
| 9 | +export interface ChatPageProps { |
| 10 | + params: { |
| 11 | + id: string; |
| 12 | + }; |
| 13 | +} |
| 14 | + |
| 15 | +export async function generateMetadata({ |
| 16 | + params, |
| 17 | +}: ChatPageProps): Promise<Metadata> { |
| 18 | + const supabase = createClient(); |
| 19 | + const { data } = await supabase.auth.getUser(); |
| 20 | + |
| 21 | + const session: Session | undefined = data?.user?.email |
| 22 | + ? { |
| 23 | + user: { |
| 24 | + id: data.user.id, |
| 25 | + email: data.user.email, |
| 26 | + }, |
| 27 | + } |
| 28 | + : undefined; |
| 29 | + |
| 30 | + if (!session?.user) { |
| 31 | + return {}; |
| 32 | + } |
| 33 | + |
| 34 | + const chat = await getChat(params.id, session.user.id); |
| 35 | + return { |
| 36 | + title: chat?.title.toString().slice(0, 50) ?? "Chat", |
| 37 | + }; |
| 38 | +} |
| 39 | + |
| 40 | +export default async function ChatPage({ params }: ChatPageProps) { |
| 41 | + const supabase = createClient(); |
| 42 | + const { data } = await supabase.auth.getUser(); |
| 43 | + const session: Session | undefined = data?.user?.email |
| 44 | + ? { |
| 45 | + user: { |
| 46 | + id: data.user.id, |
| 47 | + email: data.user.email, |
| 48 | + }, |
| 49 | + } |
| 50 | + : undefined; |
| 51 | + const missingKeys: string[] = []; |
| 52 | + |
| 53 | + if (!session?.user) { |
| 54 | + redirect(`/login?next=/chat/${params.id}`); |
| 55 | + } |
| 56 | + |
| 57 | + const userId = session.user.id as string; |
| 58 | + const chat = await getChat(params.id, userId); |
| 59 | + |
| 60 | + if (!chat) { |
| 61 | + redirect("/"); |
| 62 | + } |
| 63 | + |
| 64 | + if (chat?.userId !== session?.user?.id) { |
| 65 | + notFound(); |
| 66 | + } |
| 67 | + |
| 68 | + return ( |
| 69 | + <AI initialAIState={{ chatId: chat.id, messages: chat.messages }}> |
| 70 | + <Chat |
| 71 | + id={chat.id} |
| 72 | + session={session} |
| 73 | + initialMessages={chat.messages} |
| 74 | + missingKeys={missingKeys} |
| 75 | + /> |
| 76 | + </AI> |
| 77 | + ); |
| 78 | +} |
0 commit comments