feat: paginate chat history (#903)

This commit is contained in:
Jeremy 2025-04-03 00:28:36 -07:00 committed by GitHub
parent 235b0edb91
commit a07a3aad5b
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
6 changed files with 346 additions and 212 deletions

View file

@ -1,14 +1,37 @@
import { auth } from '@/app/(auth)/auth'; import { auth } from '@/app/(auth)/auth';
import { NextRequest } from 'next/server';
import { getChatsByUserId } from '@/lib/db/queries'; import { getChatsByUserId } from '@/lib/db/queries';
export async function GET() { export async function GET(request: NextRequest) {
const { searchParams } = request.nextUrl;
const limit = parseInt(searchParams.get('limit') || '10');
const startingAfter = searchParams.get('starting_after');
const endingBefore = searchParams.get('ending_before');
if (startingAfter && endingBefore) {
return Response.json(
'Only one of starting_after or ending_before can be provided!',
{ status: 400 },
);
}
const session = await auth(); const session = await auth();
if (!session || !session.user) { if (!session?.user?.id) {
return Response.json('Unauthorized!', { status: 401 }); return Response.json('Unauthorized!', { status: 401 });
} }
// biome-ignore lint: Forbidden non-null assertion. try {
const chats = await getChatsByUserId({ id: session.user.id! }); const chats = await getChatsByUserId({
return Response.json(chats); id: session.user.id,
limit,
startingAfter,
endingBefore,
});
return Response.json(chats);
} catch (_) {
return Response.json('Failed to fetch chats!', { status: 500 });
}
} }

View file

@ -10,9 +10,11 @@ import { fetcher, generateUUID } from '@/lib/utils';
import { Artifact } from './artifact'; import { Artifact } from './artifact';
import { MultimodalInput } from './multimodal-input'; import { MultimodalInput } from './multimodal-input';
import { Messages } from './messages'; import { Messages } from './messages';
import { VisibilityType } from './visibility-selector'; import type { VisibilityType } from './visibility-selector';
import { useArtifactSelector } from '@/hooks/use-artifact'; import { useArtifactSelector } from '@/hooks/use-artifact';
import { toast } from 'sonner'; import { toast } from 'sonner';
import { unstable_serialize } from 'swr/infinite';
import { getChatHistoryPaginationKey } from './sidebar-history';
export function Chat({ export function Chat({
id, id,
@ -47,7 +49,7 @@ export function Chat({
sendExtraMessageFields: true, sendExtraMessageFields: true,
generateId: generateUUID, generateId: generateUUID,
onFinish: () => { onFinish: () => {
mutate('/api/history'); mutate(unstable_serialize(getChatHistoryPaginationKey));
}, },
onError: () => { onError: () => {
toast.error('An error occured, please try again!'); toast.error('An error occured, please try again!');

View file

@ -0,0 +1,118 @@
import { Chat } from '@/lib/db/schema';
import {
SidebarMenuAction,
SidebarMenuButton,
SidebarMenuItem,
} from './ui/sidebar';
import Link from 'next/link';
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuPortal,
DropdownMenuSub,
DropdownMenuSubContent,
DropdownMenuSubTrigger,
DropdownMenuTrigger,
} from './ui/dropdown-menu';
import {
CheckCircleFillIcon,
GlobeIcon,
LockIcon,
MoreHorizontalIcon,
ShareIcon,
TrashIcon,
} from './icons';
import { memo } from 'react';
import { useChatVisibility } from '@/hooks/use-chat-visibility';
const PureChatItem = ({
chat,
isActive,
onDelete,
setOpenMobile,
}: {
chat: Chat;
isActive: boolean;
onDelete: (chatId: string) => void;
setOpenMobile: (open: boolean) => void;
}) => {
const { visibilityType, setVisibilityType } = useChatVisibility({
chatId: chat.id,
initialVisibility: chat.visibility,
});
return (
<SidebarMenuItem>
<SidebarMenuButton asChild isActive={isActive}>
<Link href={`/chat/${chat.id}`} onClick={() => setOpenMobile(false)}>
<span>{chat.title}</span>
</Link>
</SidebarMenuButton>
<DropdownMenu modal={true}>
<DropdownMenuTrigger asChild>
<SidebarMenuAction
className="data-[state=open]:bg-sidebar-accent data-[state=open]:text-sidebar-accent-foreground mr-0.5"
showOnHover={!isActive}
>
<MoreHorizontalIcon />
<span className="sr-only">More</span>
</SidebarMenuAction>
</DropdownMenuTrigger>
<DropdownMenuContent side="bottom" align="end">
<DropdownMenuSub>
<DropdownMenuSubTrigger className="cursor-pointer">
<ShareIcon />
<span>Share</span>
</DropdownMenuSubTrigger>
<DropdownMenuPortal>
<DropdownMenuSubContent>
<DropdownMenuItem
className="cursor-pointer flex-row justify-between"
onClick={() => {
setVisibilityType('private');
}}
>
<div className="flex flex-row gap-2 items-center">
<LockIcon size={12} />
<span>Private</span>
</div>
{visibilityType === 'private' ? (
<CheckCircleFillIcon />
) : null}
</DropdownMenuItem>
<DropdownMenuItem
className="cursor-pointer flex-row justify-between"
onClick={() => {
setVisibilityType('public');
}}
>
<div className="flex flex-row gap-2 items-center">
<GlobeIcon />
<span>Public</span>
</div>
{visibilityType === 'public' ? <CheckCircleFillIcon /> : null}
</DropdownMenuItem>
</DropdownMenuSubContent>
</DropdownMenuPortal>
</DropdownMenuSub>
<DropdownMenuItem
className="cursor-pointer text-destructive focus:bg-destructive/15 focus:text-destructive dark:text-red-500"
onSelect={() => onDelete(chat.id)}
>
<TrashIcon />
<span>Delete</span>
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
</SidebarMenuItem>
);
};
export const ChatItem = memo(PureChatItem, (prevProps, nextProps) => {
if (prevProps.isActive !== nextProps.isActive) return false;
return true;
});

View file

@ -1,21 +1,11 @@
'use client'; 'use client';
import { isToday, isYesterday, subMonths, subWeeks } from 'date-fns'; import { isToday, isYesterday, subMonths, subWeeks } from 'date-fns';
import Link from 'next/link'; import { useParams, useRouter } from 'next/navigation';
import { useParams, usePathname, useRouter } from 'next/navigation';
import type { User } from 'next-auth'; import type { User } from 'next-auth';
import { memo, useEffect, useState } from 'react'; import { useState } from 'react';
import { toast } from 'sonner'; import { toast } from 'sonner';
import useSWR from 'swr'; import { motion } from 'framer-motion';
import {
CheckCircleFillIcon,
GlobeIcon,
LockIcon,
MoreHorizontalIcon,
ShareIcon,
TrashIcon,
} from '@/components/icons';
import { import {
AlertDialog, AlertDialog,
AlertDialogAction, AlertDialogAction,
@ -26,29 +16,17 @@ import {
AlertDialogHeader, AlertDialogHeader,
AlertDialogTitle, AlertDialogTitle,
} from '@/components/ui/alert-dialog'; } from '@/components/ui/alert-dialog';
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuPortal,
DropdownMenuSeparator,
DropdownMenuSub,
DropdownMenuSubContent,
DropdownMenuSubTrigger,
DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import { import {
SidebarGroup, SidebarGroup,
SidebarGroupContent, SidebarGroupContent,
SidebarMenu, SidebarMenu,
SidebarMenuAction,
SidebarMenuButton,
SidebarMenuItem,
useSidebar, useSidebar,
} from '@/components/ui/sidebar'; } from '@/components/ui/sidebar';
import type { Chat } from '@/lib/db/schema'; import type { Chat } from '@/lib/db/schema';
import { fetcher } from '@/lib/utils'; import { fetcher } from '@/lib/utils';
import { useChatVisibility } from '@/hooks/use-chat-visibility'; import { ChatItem } from './sidebar-history-item';
import useSWRInfinite from 'swr/infinite';
import { LoaderIcon } from './icons';
type GroupedChats = { type GroupedChats = {
today: Chat[]; today: Chat[];
@ -58,116 +36,89 @@ type GroupedChats = {
older: Chat[]; older: Chat[];
}; };
const PureChatItem = ({ export interface ChatHistory {
chat, chats: Array<Chat>;
isActive, hasMore: boolean;
onDelete, }
setOpenMobile,
}: {
chat: Chat;
isActive: boolean;
onDelete: (chatId: string) => void;
setOpenMobile: (open: boolean) => void;
}) => {
const { visibilityType, setVisibilityType } = useChatVisibility({
chatId: chat.id,
initialVisibility: chat.visibility,
});
return ( const PAGE_SIZE = 20;
<SidebarMenuItem>
<SidebarMenuButton asChild isActive={isActive}>
<Link href={`/chat/${chat.id}`} onClick={() => setOpenMobile(false)}>
<span>{chat.title}</span>
</Link>
</SidebarMenuButton>
<DropdownMenu modal={true}> const groupChatsByDate = (chats: Chat[]): GroupedChats => {
<DropdownMenuTrigger asChild> const now = new Date();
<SidebarMenuAction const oneWeekAgo = subWeeks(now, 1);
className="data-[state=open]:bg-sidebar-accent data-[state=open]:text-sidebar-accent-foreground mr-0.5" const oneMonthAgo = subMonths(now, 1);
showOnHover={!isActive}
>
<MoreHorizontalIcon />
<span className="sr-only">More</span>
</SidebarMenuAction>
</DropdownMenuTrigger>
<DropdownMenuContent side="bottom" align="end"> return chats.reduce(
<DropdownMenuSub> (groups, chat) => {
<DropdownMenuSubTrigger className="cursor-pointer"> const chatDate = new Date(chat.createdAt);
<ShareIcon />
<span>Share</span>
</DropdownMenuSubTrigger>
<DropdownMenuPortal>
<DropdownMenuSubContent>
<DropdownMenuItem
className="cursor-pointer flex-row justify-between"
onClick={() => {
setVisibilityType('private');
}}
>
<div className="flex flex-row gap-2 items-center">
<LockIcon size={12} />
<span>Private</span>
</div>
{visibilityType === 'private' ? (
<CheckCircleFillIcon />
) : null}
</DropdownMenuItem>
<DropdownMenuItem
className="cursor-pointer flex-row justify-between"
onClick={() => {
setVisibilityType('public');
}}
>
<div className="flex flex-row gap-2 items-center">
<GlobeIcon />
<span>Public</span>
</div>
{visibilityType === 'public' ? <CheckCircleFillIcon /> : null}
</DropdownMenuItem>
</DropdownMenuSubContent>
</DropdownMenuPortal>
</DropdownMenuSub>
<DropdownMenuItem if (isToday(chatDate)) {
className="cursor-pointer text-destructive focus:bg-destructive/15 focus:text-destructive dark:text-red-500" groups.today.push(chat);
onSelect={() => onDelete(chat.id)} } else if (isYesterday(chatDate)) {
> groups.yesterday.push(chat);
<TrashIcon /> } else if (chatDate > oneWeekAgo) {
<span>Delete</span> groups.lastWeek.push(chat);
</DropdownMenuItem> } else if (chatDate > oneMonthAgo) {
</DropdownMenuContent> groups.lastMonth.push(chat);
</DropdownMenu> } else {
</SidebarMenuItem> groups.older.push(chat);
}
return groups;
},
{
today: [],
yesterday: [],
lastWeek: [],
lastMonth: [],
older: [],
} as GroupedChats,
); );
}; };
export const ChatItem = memo(PureChatItem, (prevProps, nextProps) => { export function getChatHistoryPaginationKey(
if (prevProps.isActive !== nextProps.isActive) return false; pageIndex: number,
return true; previousPageData: ChatHistory,
}); ) {
if (previousPageData && previousPageData.hasMore === false) {
return null;
}
if (pageIndex === 0) return `/api/history?limit=${PAGE_SIZE}`;
const firstChatFromPage = previousPageData.chats.at(-1);
if (!firstChatFromPage) return null;
return `/api/history?ending_before=${firstChatFromPage.id}&limit=${PAGE_SIZE}`;
}
export function SidebarHistory({ user }: { user: User | undefined }) { export function SidebarHistory({ user }: { user: User | undefined }) {
const { setOpenMobile } = useSidebar(); const { setOpenMobile } = useSidebar();
const { id } = useParams(); const { id } = useParams();
const pathname = usePathname();
const { const {
data: history, data: paginatedChatHistories,
setSize,
isValidating,
isLoading, isLoading,
mutate, mutate,
} = useSWR<Array<Chat>>(user ? '/api/history' : null, fetcher, { } = useSWRInfinite<ChatHistory>(getChatHistoryPaginationKey, fetcher, {
fallbackData: [], fallbackData: [],
}); });
useEffect(() => { const router = useRouter();
mutate();
}, [pathname, mutate]);
const [deleteId, setDeleteId] = useState<string | null>(null); const [deleteId, setDeleteId] = useState<string | null>(null);
const [showDeleteDialog, setShowDeleteDialog] = useState(false); const [showDeleteDialog, setShowDeleteDialog] = useState(false);
const router = useRouter();
const hasReachedEnd = paginatedChatHistories
? paginatedChatHistories.some((page) => page.hasMore === false)
: false;
const hasEmptyChatHistory = paginatedChatHistories
? paginatedChatHistories.every((page) => page.chats.length === 0)
: false;
const handleDelete = async () => { const handleDelete = async () => {
const deletePromise = fetch(`/api/chat?id=${deleteId}`, { const deletePromise = fetch(`/api/chat?id=${deleteId}`, {
method: 'DELETE', method: 'DELETE',
@ -176,11 +127,15 @@ export function SidebarHistory({ user }: { user: User | undefined }) {
toast.promise(deletePromise, { toast.promise(deletePromise, {
loading: 'Deleting chat...', loading: 'Deleting chat...',
success: () => { success: () => {
mutate((history) => { mutate((chatHistories) => {
if (history) { if (chatHistories) {
return history.filter((h) => h.id !== id); return chatHistories.map((chatHistory) => ({
...chatHistory,
chats: chatHistory.chats.filter((chat) => chat.id !== deleteId),
}));
} }
}); });
return 'Chat deleted successfully'; return 'Chat deleted successfully';
}, },
error: 'Failed to delete chat', error: 'Failed to delete chat',
@ -234,7 +189,7 @@ export function SidebarHistory({ user }: { user: User | undefined }) {
); );
} }
if (history?.length === 0) { if (hasEmptyChatHistory) {
return ( return (
<SidebarGroup> <SidebarGroup>
<SidebarGroupContent> <SidebarGroupContent>
@ -246,52 +201,23 @@ export function SidebarHistory({ user }: { user: User | undefined }) {
); );
} }
const groupChatsByDate = (chats: Chat[]): GroupedChats => {
const now = new Date();
const oneWeekAgo = subWeeks(now, 1);
const oneMonthAgo = subMonths(now, 1);
return chats.reduce(
(groups, chat) => {
const chatDate = new Date(chat.createdAt);
if (isToday(chatDate)) {
groups.today.push(chat);
} else if (isYesterday(chatDate)) {
groups.yesterday.push(chat);
} else if (chatDate > oneWeekAgo) {
groups.lastWeek.push(chat);
} else if (chatDate > oneMonthAgo) {
groups.lastMonth.push(chat);
} else {
groups.older.push(chat);
}
return groups;
},
{
today: [],
yesterday: [],
lastWeek: [],
lastMonth: [],
older: [],
} as GroupedChats,
);
};
return ( return (
<> <>
<SidebarGroup> <SidebarGroup>
<SidebarGroupContent> <SidebarGroupContent>
<SidebarMenu> <SidebarMenu>
{history && {paginatedChatHistories &&
(() => { (() => {
const groupedChats = groupChatsByDate(history); const chatsFromHistory = paginatedChatHistories.flatMap(
(paginatedChatHistory) => paginatedChatHistory.chats,
);
const groupedChats = groupChatsByDate(chatsFromHistory);
return ( return (
<> <div className="flex flex-col gap-6">
{groupedChats.today.length > 0 && ( {groupedChats.today.length > 0 && (
<> <div>
<div className="px-2 py-1 text-xs text-sidebar-foreground/50"> <div className="px-2 py-1 text-xs text-sidebar-foreground/50">
Today Today
</div> </div>
@ -307,12 +233,12 @@ export function SidebarHistory({ user }: { user: User | undefined }) {
setOpenMobile={setOpenMobile} setOpenMobile={setOpenMobile}
/> />
))} ))}
</> </div>
)} )}
{groupedChats.yesterday.length > 0 && ( {groupedChats.yesterday.length > 0 && (
<> <div>
<div className="px-2 py-1 text-xs text-sidebar-foreground/50 mt-6"> <div className="px-2 py-1 text-xs text-sidebar-foreground/50">
Yesterday Yesterday
</div> </div>
{groupedChats.yesterday.map((chat) => ( {groupedChats.yesterday.map((chat) => (
@ -327,12 +253,12 @@ export function SidebarHistory({ user }: { user: User | undefined }) {
setOpenMobile={setOpenMobile} setOpenMobile={setOpenMobile}
/> />
))} ))}
</> </div>
)} )}
{groupedChats.lastWeek.length > 0 && ( {groupedChats.lastWeek.length > 0 && (
<> <div>
<div className="px-2 py-1 text-xs text-sidebar-foreground/50 mt-6"> <div className="px-2 py-1 text-xs text-sidebar-foreground/50">
Last 7 days Last 7 days
</div> </div>
{groupedChats.lastWeek.map((chat) => ( {groupedChats.lastWeek.map((chat) => (
@ -347,12 +273,12 @@ export function SidebarHistory({ user }: { user: User | undefined }) {
setOpenMobile={setOpenMobile} setOpenMobile={setOpenMobile}
/> />
))} ))}
</> </div>
)} )}
{groupedChats.lastMonth.length > 0 && ( {groupedChats.lastMonth.length > 0 && (
<> <div>
<div className="px-2 py-1 text-xs text-sidebar-foreground/50 mt-6"> <div className="px-2 py-1 text-xs text-sidebar-foreground/50">
Last 30 days Last 30 days
</div> </div>
{groupedChats.lastMonth.map((chat) => ( {groupedChats.lastMonth.map((chat) => (
@ -367,13 +293,13 @@ export function SidebarHistory({ user }: { user: User | undefined }) {
setOpenMobile={setOpenMobile} setOpenMobile={setOpenMobile}
/> />
))} ))}
</> </div>
)} )}
{groupedChats.older.length > 0 && ( {groupedChats.older.length > 0 && (
<> <div>
<div className="px-2 py-1 text-xs text-sidebar-foreground/50 mt-6"> <div className="px-2 py-1 text-xs text-sidebar-foreground/50">
Older Older than last month
</div> </div>
{groupedChats.older.map((chat) => ( {groupedChats.older.map((chat) => (
<ChatItem <ChatItem
@ -387,14 +313,36 @@ export function SidebarHistory({ user }: { user: User | undefined }) {
setOpenMobile={setOpenMobile} setOpenMobile={setOpenMobile}
/> />
))} ))}
</> </div>
)} )}
</> </div>
); );
})()} })()}
</SidebarMenu> </SidebarMenu>
<motion.div
onViewportEnter={() => {
if (!isValidating && !hasReachedEnd) {
setSize((size) => size + 1);
}
}}
/>
{hasReachedEnd ? (
<div className="px-2 text-zinc-500 w-full flex flex-row justify-center items-center text-sm gap-2 mt-8">
You have reached the end of your chat history.
</div>
) : (
<div className="p-2 text-zinc-500 dark:text-zinc-400 flex flex-row gap-2 items-center mt-8">
<div className="animate-spin">
<LoaderIcon />
</div>
<div>Loading Chats...</div>
</div>
)}
</SidebarGroupContent> </SidebarGroupContent>
</SidebarGroup> </SidebarGroup>
<AlertDialog open={showDeleteDialog} onOpenChange={setShowDeleteDialog}> <AlertDialog open={showDeleteDialog} onOpenChange={setShowDeleteDialog}>
<AlertDialogContent> <AlertDialogContent>
<AlertDialogHeader> <AlertDialogHeader>

View file

@ -1,10 +1,14 @@
'use client'; 'use client';
import { updateChatVisibility } from '@/app/(chat)/actions';
import { VisibilityType } from '@/components/visibility-selector';
import { Chat } from '@/lib/db/schema';
import { useMemo } from 'react'; import { useMemo } from 'react';
import useSWR, { useSWRConfig } from 'swr'; import useSWR, { useSWRConfig } from 'swr';
import { unstable_serialize } from 'swr/infinite';
import { updateChatVisibility } from '@/app/(chat)/actions';
import {
getChatHistoryPaginationKey,
type ChatHistory,
} from '@/components/sidebar-history';
import type { VisibilityType } from '@/components/visibility-selector';
export function useChatVisibility({ export function useChatVisibility({
chatId, chatId,
@ -14,7 +18,7 @@ export function useChatVisibility({
initialVisibility: VisibilityType; initialVisibility: VisibilityType;
}) { }) {
const { mutate, cache } = useSWRConfig(); const { mutate, cache } = useSWRConfig();
const history: Array<Chat> = cache.get('/api/history')?.data; const history: ChatHistory = cache.get('/api/history')?.data;
const { data: localVisibility, mutate: setLocalVisibility } = useSWR( const { data: localVisibility, mutate: setLocalVisibility } = useSWR(
`${chatId}-visibility`, `${chatId}-visibility`,
@ -26,31 +30,14 @@ export function useChatVisibility({
const visibilityType = useMemo(() => { const visibilityType = useMemo(() => {
if (!history) return localVisibility; if (!history) return localVisibility;
const chat = history.find((chat) => chat.id === chatId); const chat = history.chats.find((chat) => chat.id === chatId);
if (!chat) return 'private'; if (!chat) return 'private';
return chat.visibility; return chat.visibility;
}, [history, chatId, localVisibility]); }, [history, chatId, localVisibility]);
const setVisibilityType = (updatedVisibilityType: VisibilityType) => { const setVisibilityType = (updatedVisibilityType: VisibilityType) => {
setLocalVisibility(updatedVisibilityType); setLocalVisibility(updatedVisibilityType);
mutate(unstable_serialize(getChatHistoryPaginationKey));
mutate<Array<Chat>>(
'/api/history',
(history) => {
return history
? history.map((chat) => {
if (chat.id === chatId) {
return {
...chat,
visibility: updatedVisibilityType,
};
}
return chat;
})
: [];
},
{ revalidate: false },
);
updateChatVisibility({ updateChatVisibility({
chatId: chatId, chatId: chatId,

View file

@ -1,7 +1,7 @@
import 'server-only'; import 'server-only';
import { genSaltSync, hashSync } from 'bcrypt-ts'; import { genSaltSync, hashSync } from 'bcrypt-ts';
import { and, asc, desc, eq, gt, gte, inArray } from 'drizzle-orm'; import { and, asc, desc, eq, gt, gte, inArray, lt, SQL } from 'drizzle-orm';
import { drizzle } from 'drizzle-orm/postgres-js'; import { drizzle } from 'drizzle-orm/postgres-js';
import postgres from 'postgres'; import postgres from 'postgres';
@ -15,6 +15,7 @@ import {
message, message,
vote, vote,
type DBMessage, type DBMessage,
Chat,
} from './schema'; } from './schema';
import { ArtifactKind } from '@/components/artifact'; import { ArtifactKind } from '@/components/artifact';
@ -81,13 +82,68 @@ export async function deleteChatById({ id }: { id: string }) {
} }
} }
export async function getChatsByUserId({ id }: { id: string }) { export async function getChatsByUserId({
id,
limit,
startingAfter,
endingBefore,
}: {
id: string;
limit: number;
startingAfter: string | null;
endingBefore: string | null;
}) {
try { try {
return await db const extendedLimit = limit + 1;
.select()
.from(chat) const query = (whereCondition?: SQL<any>) =>
.where(eq(chat.userId, id)) db
.orderBy(desc(chat.createdAt)); .select()
.from(chat)
.where(
whereCondition
? and(whereCondition, eq(chat.userId, id))
: eq(chat.userId, id),
)
.orderBy(desc(chat.createdAt))
.limit(extendedLimit);
let filteredChats: Array<Chat> = [];
if (startingAfter) {
const [selectedChat] = await db
.select()
.from(chat)
.where(eq(chat.id, startingAfter))
.limit(1);
if (!selectedChat) {
throw new Error(`Chat with id ${startingAfter} not found`);
}
filteredChats = await query(gt(chat.createdAt, selectedChat.createdAt));
} else if (endingBefore) {
const [selectedChat] = await db
.select()
.from(chat)
.where(eq(chat.id, endingBefore))
.limit(1);
if (!selectedChat) {
throw new Error(`Chat with id ${endingBefore} not found`);
}
filteredChats = await query(lt(chat.createdAt, selectedChat.createdAt));
} else {
filteredChats = await query();
}
const hasMore = filteredChats.length > limit;
return {
chats: hasMore ? filteredChats.slice(0, limit) : filteredChats,
hasMore,
};
} catch (error) { } catch (error) {
console.error('Failed to get chats by user from database'); console.error('Failed to get chats by user from database');
throw error; throw error;