53129
Pa
PAT / files
PAT / app / api / threads / route.ts
1.8 KB
1import { db } from "@/src/lib/db"; 2import { threads } from "@/src/lib/db/schema"; 3import { debug } from "@/src/lib/debug"; 4import { createThread } from "@/src/lib/threads"; 5import { count, desc } from "drizzle-orm"; 6import { NextResponse } from "next/server"; 7 8export async function POST(request: Request) { 9 try { 10 const { userMessage, model, maxPromptLength, userPrompt, time, timezone } = 11 await request.json(); 12 13 if (!model || !userMessage) { 14 return NextResponse.json({ error: "Model and user message are required" }, { status: 400 }); 15 } 16 17 const thread = await createThread( 18 userMessage, 19 model, 20 maxPromptLength, 21 userPrompt, 22 time, 23 timezone 24 ); 25 return NextResponse.json({ thread }); 26 } catch (err) { 27 debug( 28 `[Threads API] Error creating thread:`, 29 err instanceof Error ? err.message : "Unknown error" 30 ); 31 return NextResponse.json({ error: "Failed to create thread" }, { status: 500 }); 32 } 33} 34 35export async function GET(request: Request) { 36 try { 37 const { searchParams } = new URL(request.url); 38 const offset = parseInt(searchParams.get("offset") || "0", 10); 39 const limit = parseInt(searchParams.get("limit") || "8", 10); 40 41 const threadsList = await db 42 .select() 43 .from(threads) 44 .orderBy(desc(threads.updatedAt)) 45 .limit(limit) 46 .offset(offset); 47 48 const totalCountResult = await db.select({ count: count() }).from(threads); 49 const totalCount = totalCountResult[0]?.count || 0; 50 const hasMore = offset + limit < totalCount; 51 52 return NextResponse.json({ threads: threadsList, hasMore, totalCount }); 53 } catch (err) { 54 debug( 55 `[Threads API] Error fetching threads:`, 56 err instanceof Error ? err.message : "Unknown error" 57 ); 58 return NextResponse.json({ error: "Failed to get threads" }, { status: 500 }); 59 } 60}