import { Router } from "@oak/oak"; import type { APIResponse } from "../../shared/api.ts"; import type { ChatMessage } from "../../shared/chat.ts"; import { authMiddleware } from "../middleware/auth.ts"; import { getChatMessagesAfter, getRecentChatMessages, } from "../services/chat-service.ts"; const router = new Router({ prefix: "/api/chat" }); // GET /api/chat — recent messages (ascending). `limit` caps the page size. // Cursors (ISO created_at, plus the message id to break ties): // before/beforeId — the page of older messages preceding it ("load older"); // after/afterId — the messages following it (resync after a reconnect); // without afterId the timestamp itself is included. router.get("/", authMiddleware, (ctx) => { const params = ctx.request.url.searchParams; const limitParam = params.get("limit"); const limit = limitParam ? Number(limitParam) : NaN; const cappedLimit = Number.isFinite(limit) ? limit : undefined; const before = params.get("before"); const after = params.get("after"); const messages = after ? getChatMessagesAfter( { createdAt: after, id: params.get("afterId") ?? undefined }, cappedLimit, ) : getRecentChatMessages( cappedLimit, before ? { createdAt: before, id: params.get("beforeId") ?? undefined } : undefined, ); const responseBody: APIResponse = { success: true, data: messages, }; ctx.response.body = responseBody; }); export default router;