Adding user session for history

Adding max record limt in settings
This commit is contained in:
sjiampojamarn 2025-04-05 15:14:25 -07:00
parent 8dc54efbdd
commit dce3a9eca0
5 changed files with 115 additions and 4 deletions

View file

@ -25,6 +25,7 @@ type Message = {
messageId: string;
chatId: string;
content: string;
userSessionId: string;
};
type ChatModel = {
@ -135,7 +136,7 @@ const handleHistorySave = async (
});
const fileData = files.map(getFileDetails);
let currentDate = new Date();
if (!chat) {
await db
.insert(chats)
@ -145,6 +146,8 @@ const handleHistorySave = async (
createdAt: new Date().toString(),
focusMode: focusMode,
files: fileData,
userSessionId: message.userSessionId,
timestamp: currentDate.toISOString(),
})
.execute();
} else if (JSON.stringify(chat.files ?? []) != JSON.stringify(fileData)) {

View file

@ -1,10 +1,47 @@
import db from '@/lib/db';
import { chats } from '@/lib/db/schema';
import { eq, sql} from 'drizzle-orm';
export const GET = async (req: Request) => {
try {
let chats = await db.query.chats.findMany();
chats = chats.reverse();
return Response.json({ chats: chats }, { status: 200 });
// get header from request
const headers = await req.headers;
const userSessionId = headers.get('user-session-id')?.toString() ?? '';
const maxRecordLimit = parseInt(headers.get('max-record-limit') || '20', 10);
if (userSessionId == '') {
return Response.json({ chats: {} }, { status: 200 });
}
let chatsRes = await db.query.chats.findMany({
where: eq(chats.userSessionId, userSessionId),
});
chatsRes = chatsRes.reverse();
// Keep only the latest records in the database. Delete older records.
if (chatsRes.length > maxRecordLimit) {
const deleteChatsQuery = sql`DELETE FROM chats
WHERE userSessionId = ${userSessionId} AND (
timestamp IS NULL OR
timestamp NOT in (
SELECT timestamp FROM chats
WHERE userSessionId = ${userSessionId}
ORDER BY timestamp DESC
LIMIT ${maxRecordLimit}
)
)
`;
await db.run(deleteChatsQuery);
// Delete messages that no longer link with the chat from the database.
const deleteMessagesQuery = sql`DELETE FROM messages
WHERE chatId NOT IN (
SELECT id FROM chats
)
`;
await db.run(deleteMessagesQuery);
}
return Response.json({ chats: chatsRes }, { status: 200 });
} catch (err) {
console.error('Error in getting chats: ', err);
return Response.json(