Fix chat API query - use separate queries instead of aggregate

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
This commit is contained in:
Manohar Gupta 2026-05-11 01:51:21 +05:30
parent 9e506279a7
commit 1c5c02ffbd

View file

@ -7,24 +7,34 @@ export async function GET(request: Request) {
const childId = searchParams.get("childId") || "default";
try {
// Single query with JOIN for better performance
const sessions = await sql.unsafe(`
SELECT
cs.id, cs.title, cs.created_at as "createdAt", cs.updated_at as "updatedAt",
COALESCE(
json_agg(
json_build_object('id', cm.id, 'role', cm.role, 'content', cm.content, 'createdAt', cm.created_at ORDER BY cm.created_at)
) FILTER (WHERE cm.id IS NOT NULL),
'[]'::json
) as messages
FROM chat_sessions cs
LEFT JOIN chat_messages cm ON cm.session_id = cs.id
WHERE cs.child_id = $1
GROUP BY cs.id
ORDER BY cs.updated_at DESC
`, [childId]);
// Fetch sessions only (messages fetched separately for better control)
const sessions = await sql`
SELECT id, title, created_at as "createdAt", updated_at as "updatedAt"
FROM chat_sessions
WHERE child_id = ${childId}
ORDER BY updated_at DESC
`;
return NextResponse.json({ sessions: sessions || [] });
// Fetch messages for all sessions in one go (if any)
const messages = await sql`
SELECT session_id, id, role, content, created_at as "createdAt"
FROM chat_messages
ORDER BY created_at
`;
// Merge messages into sessions
const msgMap = new Map();
(messages || []).forEach((m: any) => {
if (!msgMap.has(m.session_id)) msgMap.set(m.session_id, []);
msgMap.get(m.session_id).push(m);
});
const sessionsWithMessages = (sessions || []).map((s: any) => ({
...s,
messages: msgMap.get(s.id) || [],
}));
return NextResponse.json({ sessions: sessionsWithMessages });
} catch (error) {
console.error(error);
return NextResponse.json({ error: String(error) }, { status: 500 });