chatbot-template/app/sidebar.tsx

70 lines
1.8 KiB
TypeScript
Raw Normal View History

2023-06-02 15:33:48 -04:00
import { Chat } from '@/lib/types'
import { type Session } from '@auth/nextjs/types'
2023-06-07 16:17:59 +04:00
import { kv } from '@vercel/kv'
import { Sidebar as SidebarIcon } from 'lucide-react'
2023-06-02 15:33:48 -04:00
import { SidebarItem } from './sidebar-item'
2023-05-19 12:33:56 -04:00
2023-06-07 16:17:59 +04:00
import { auth } from '@/auth'
import { NextChat } from '@/components/icons'
import { Button } from '@/components/ui/button'
import { Sheet, SheetContent, SheetTrigger } from '@/components/ui/sheet'
2023-05-19 12:33:56 -04:00
2023-06-07 16:17:59 +04:00
export interface SidebarProps {}
2023-05-19 12:33:56 -04:00
2023-06-07 16:17:59 +04:00
export async function Sidebar({}: SidebarProps) {
const session = await auth()
2023-05-23 16:49:07 +02:00
2023-06-07 16:17:59 +04:00
return (
<Sheet>
<SheetTrigger asChild>
<Button variant="ghost" className="w-9 h-9 p-0">
<SidebarIcon className="w-6 h-6" />
<span className="sr-only">Toggle Sidebar</span>
</Button>
</SheetTrigger>
<SheetContent
position="left"
className="w-[300px] top-2 rounded-lg left-2 bottom-2 h-auto"
>
<div className="flex items-center">
<NextChat className="mr-2 w-6 h-6 text-primary" inverted />
<span className="select-none font-bold">Chatbot</span>
2023-05-19 12:33:56 -04:00
</div>
2023-06-07 16:17:59 +04:00
{/* @ts-ignore */}
<SidebarList session={session} />
</SheetContent>
</Sheet>
2023-06-02 15:33:48 -04:00
)
2023-05-19 12:33:56 -04:00
}
async function SidebarList({ session }: { session?: Session }) {
2023-06-02 15:33:48 -04:00
const results: Chat[] = await getChats(session?.user?.email ?? '')
2023-05-22 13:37:56 +02:00
2023-06-02 15:33:48 -04:00
return results.map(c => (
2023-06-02 14:28:05 -04:00
<SidebarItem
key={c.id}
title={c.title}
2023-06-02 15:33:48 -04:00
userId={session?.user?.email ?? ''}
2023-06-02 14:28:05 -04:00
href={`/chat/${c.id}`}
id={c.id}
/>
2023-06-02 15:33:48 -04:00
))
2023-05-19 12:33:56 -04:00
}
2023-06-02 15:15:35 -04:00
async function getChats(userId: string) {
try {
2023-06-02 15:33:48 -04:00
const pipeline = kv.pipeline()
const chats: string[] = await kv.zrange(`user:chat:${userId}`, 0, -1)
2023-06-02 15:15:35 -04:00
for (const chat of chats) {
2023-06-02 15:33:48 -04:00
pipeline.hgetall(chat)
2023-06-02 15:15:35 -04:00
}
2023-06-02 15:33:48 -04:00
const results = await pipeline.exec()
2023-06-02 15:15:35 -04:00
2023-06-02 15:33:48 -04:00
return results as Chat[]
2023-06-02 15:15:35 -04:00
} catch (error) {
2023-06-02 15:33:48 -04:00
return []
2023-06-02 15:15:35 -04:00
}
}