import { and, asc, eq } from "drizzle-orm"; import { messages, topics } from "~~/db/schema"; import { protectRoute } from "~~/server/utils/auth"; import type { Message, Topic } from '~~/types' export default defineEventHandler(async (event) => { await protectRoute(event); const db = useDrizzle(); const userId = event.context.user.id; const topicId = getRouterParam(event, 'id'); if (!topicId) { throw createError({ statusCode: 400, statusMessage: 'Topic ID is required' }); } const rows = await db .select() .from(topics) .where(and(eq(topics.userId, userId), eq(topics.id, topicId))); if (rows.length === 0) { throw createError({ statusCode: 404, statusMessage: 'Topic not found' }); } const topic = rows[0] as Topic & { messages: Message[] }; // Fetch messages for this topic, ordered chronologically topic.messages = await db .select() .from(messages) .where(eq(messages.topicId, topic.id)) .orderBy(asc(messages.createdAt)); return topic; });