|
| 1 | +import { NextResponse } from "next/server"; |
| 2 | +import { fetchWithSecretKey } from "../serverUtils"; |
| 3 | + |
| 4 | +const NEBULA_CHAT_ENDPOINT = process.env.NEBULA_CHAT_ENDPOINT; |
| 5 | + |
| 6 | +export async function POST(request: Request) { |
| 7 | + if (!NEBULA_CHAT_ENDPOINT) { |
| 8 | + throw new Error("Chat endpoint is not defined"); |
| 9 | + } |
| 10 | + |
| 11 | + try { |
| 12 | + const body = await request.json(); |
| 13 | + const { message, user_id, session_id } = body; |
| 14 | + const secretKey = request.headers.get("x-thirdweb-key"); |
| 15 | + |
| 16 | + if (!message) { |
| 17 | + return NextResponse.json( |
| 18 | + { error: "Missing message parameter" }, |
| 19 | + { status: 400 }, |
| 20 | + ); |
| 21 | + } |
| 22 | + if (!secretKey) { |
| 23 | + return NextResponse.json( |
| 24 | + { error: "Missing ThirdWeb API key" }, |
| 25 | + { status: 401 }, |
| 26 | + ); |
| 27 | + } |
| 28 | + |
| 29 | + try { |
| 30 | + const data = await fetchWithSecretKey({ |
| 31 | + endpoint: NEBULA_CHAT_ENDPOINT, |
| 32 | + body: { message, user_id, session_id }, |
| 33 | + secretKey, |
| 34 | + timeout: 60000, // 1 minute timeout for chat requests |
| 35 | + }); |
| 36 | + |
| 37 | + return NextResponse.json(data); |
| 38 | + } catch (error: unknown) { |
| 39 | + console.error( |
| 40 | + "Chat API Error:", |
| 41 | + error instanceof Error ? error.stack : error, |
| 42 | + ); |
| 43 | + if (error instanceof Error && error.message.includes("timed out")) { |
| 44 | + return NextResponse.json( |
| 45 | + { error: "Request timed out. Please try again." }, |
| 46 | + { status: 504 }, |
| 47 | + ); |
| 48 | + } |
| 49 | + |
| 50 | + if (error instanceof Error && error.message.includes("401")) { |
| 51 | + return NextResponse.json( |
| 52 | + { error: "Invalid Authorization header" }, |
| 53 | + { status: 401 }, |
| 54 | + ); |
| 55 | + } |
| 56 | + return NextResponse.json( |
| 57 | + { |
| 58 | + error: |
| 59 | + error instanceof Error ? error.message : "Failed to fetch from API", |
| 60 | + }, |
| 61 | + { status: 500 }, |
| 62 | + ); |
| 63 | + } |
| 64 | + } catch (error) { |
| 65 | + console.error( |
| 66 | + "Request Error:", |
| 67 | + error instanceof Error ? error.stack : error, |
| 68 | + ); |
| 69 | + return NextResponse.json({ error: "Invalid request" }, { status: 400 }); |
| 70 | + } |
| 71 | +} |
0 commit comments