diff --git a/app/api/assistant/[assistant_id]/route.ts b/app/api/assistant/[assistant_id]/route.ts index b25a15f..0840b7b 100644 --- a/app/api/assistant/[assistant_id]/route.ts +++ b/app/api/assistant/[assistant_id]/route.ts @@ -1,4 +1,5 @@ -import { NextRequest, NextResponse } from 'next/server'; +import { NextRequest, NextResponse } from "next/server"; +import { apiClient } from "@/app/lib/apiClient"; /** * GET /api/assistant/:assistant_id @@ -7,46 +8,25 @@ import { NextRequest, NextResponse } from 'next/server'; */ export async function GET( request: NextRequest, - { params }: { params: Promise<{ assistant_id: string }> } + { params }: { params: Promise<{ assistant_id: string }> }, ) { try { - // Get the API key from request headers - const apiKey = request.headers.get('X-API-KEY'); - - if (!apiKey) { - return NextResponse.json( - { error: 'Missing X-API-KEY header' }, - { status: 401 } - ); - } - const { assistant_id } = await params; - // Get backend URL from environment variable - const backendUrl = process.env.BACKEND_URL || 'http://localhost:8000'; - - // Forward the request to the actual backend - const response = await fetch(`${backendUrl}/api/v1/assistant/${assistant_id}`, { - method: 'GET', - headers: { - 'X-API-KEY': apiKey, - }, - }); - - // Get the response data - const data = await response.json(); - - // Return the response with the same status code - if (!response.ok) { - return NextResponse.json(data, { status: response.status }); - } + const { status, data } = await apiClient( + request, + `/api/v1/assistant/${assistant_id}`, + ); - return NextResponse.json(data, { status: 200 }); + return NextResponse.json(data, { status }); } catch (error: unknown) { - console.error('Proxy error:', error); + console.error("Proxy error:", error); return NextResponse.json( - { error: 'Failed to forward request to backend', details: error instanceof Error ? error.message : String(error) }, - { status: 500 } + { + error: "Failed to forward request to backend", + details: error instanceof Error ? error.message : String(error), + }, + { status: 500 }, ); } } diff --git a/app/api/collections/[collection_id]/route.ts b/app/api/collections/[collection_id]/route.ts index 8892c76..bee11a0 100644 --- a/app/api/collections/[collection_id]/route.ts +++ b/app/api/collections/[collection_id]/route.ts @@ -1,44 +1,27 @@ -import { NextResponse } from 'next/server'; - -const backendUrl = process.env.BACKEND_URL || 'http://localhost:8000'; +import { NextResponse } from "next/server"; +import { apiClient } from "@/app/lib/apiClient"; // GET /api/collections/[collection_id] - Get a specific collection export async function GET( request: Request, - { params }: { params: Promise<{ collection_id: string }> } + { params }: { params: Promise<{ collection_id: string }> }, ) { const { collection_id } = await params; - const apiKey = request.headers.get('X-API-KEY'); - - if (!apiKey) { - return NextResponse.json( - { error: 'Missing X-API-KEY header' }, - { status: 401 } - ); - } - try { - const response = await fetch( - `${backendUrl}/api/v1/collections/${collection_id}?include_docs=true&include_url=true`, - { - headers: { - 'X-API-KEY': apiKey, - }, - } + const { status, data } = await apiClient( + request, + `/api/v1/collections/${collection_id}?include_docs=true&include_url=true`, ); - const text = await response.text(); - const data = text ? JSON.parse(text) : {}; - - if (!response.ok) { - return NextResponse.json(data, { status: response.status }); - } - - return NextResponse.json(data, { status: response.status }); + return NextResponse.json(data, { status }); } catch (error: unknown) { return NextResponse.json( - { success: false, error: error instanceof Error ? error.message : String(error), data: null }, - { status: 500 } + { + success: false, + error: error instanceof Error ? error.message : String(error), + data: null, + }, + { status: 500 }, ); } } @@ -46,41 +29,28 @@ export async function GET( // DELETE /api/collection/[collection_id] - Delete a collection export async function DELETE( request: Request, - { params }: { params: Promise<{ collection_id: string }> } + { params }: { params: Promise<{ collection_id: string }> }, ) { const { collection_id } = await params; - const apiKey = request.headers.get('X-API-KEY'); - - if (!apiKey) { - return NextResponse.json( - { error: 'Missing X-API-KEY header' }, - { status: 401 } - ); - } try { - const response = await fetch( - `${backendUrl}/api/v1/collections/${collection_id}`, + const { status, data } = await apiClient( + request, + `/api/v1/collections/${collection_id}`, { - method: 'DELETE', - headers: { - 'X-API-KEY': apiKey, - }, - } + method: "DELETE", + }, ); - const text = await response.text(); - const data = text ? JSON.parse(text) : { success: true }; - - if (!response.ok) { - return NextResponse.json(data, { status: response.status }); - } - - return NextResponse.json(data, { status: response.status }); + return NextResponse.json(data ?? { success: true }, { status }); } catch (error: unknown) { return NextResponse.json( - { success: false, error: error instanceof Error ? error.message : String(error), data: null }, - { status: 500 } + { + success: false, + error: error instanceof Error ? error.message : String(error), + data: null, + }, + { status: 500 }, ); } } diff --git a/app/api/collections/jobs/[job_id]/route.ts b/app/api/collections/jobs/[job_id]/route.ts index 37180c1..86a878b 100644 --- a/app/api/collections/jobs/[job_id]/route.ts +++ b/app/api/collections/jobs/[job_id]/route.ts @@ -1,44 +1,28 @@ -import { NextResponse } from 'next/server'; - -const backendUrl = process.env.BACKEND_URL || 'http://localhost:8000'; +import { NextResponse } from "next/server"; +import { apiClient } from "@/app/lib/apiClient"; // GET /api/collections/jobs/[job_id] - Get collection job status export async function GET( request: Request, - { params }: { params: Promise<{ job_id: string }> } + { params }: { params: Promise<{ job_id: string }> }, ) { const { job_id } = await params; - const apiKey = request.headers.get('X-API-KEY'); - - if (!apiKey) { - return NextResponse.json( - { error: 'Missing X-API-KEY header' }, - { status: 401 } - ); - } try { - const response = await fetch( - `${backendUrl}/api/v1/collections/jobs/${job_id}`, - { - headers: { - 'X-API-KEY': apiKey, - }, - } + const { status, data } = await apiClient( + request, + `/api/v1/collections/jobs/${job_id}`, ); - const text = await response.text(); - const data = text ? JSON.parse(text) : {}; - - if (!response.ok) { - return NextResponse.json(data, { status: response.status }); - } - - return NextResponse.json(data, { status: response.status }); + return NextResponse.json(data, { status }); } catch (error: unknown) { return NextResponse.json( - { success: false, error: error instanceof Error ? error.message : String(error), data: null }, - { status: 500 } + { + success: false, + error: error instanceof Error ? error.message : String(error), + data: null, + }, + { status: 500 }, ); } } diff --git a/app/api/collections/route.ts b/app/api/collections/route.ts index 2d4033d..0c40145 100644 --- a/app/api/collections/route.ts +++ b/app/api/collections/route.ts @@ -1,84 +1,41 @@ -import { NextRequest, NextResponse } from 'next/server'; - +import { NextRequest, NextResponse } from "next/server"; +import { apiClient } from "@/app/lib/apiClient"; export async function GET(request: Request) { - const backendUrl = process.env.BACKEND_URL || 'http://localhost:8000'; - const apiKey = request.headers.get('X-API-KEY'); - - if (!apiKey) { - return NextResponse.json( - { error: 'Missing X-API-KEY header' }, - { status: 401 } - ); - } - try { - const response = await fetch(`${backendUrl}/api/v1/collections/`, { - headers: { - 'X-API-KEY': apiKey, - }, - }); - - // Handle empty responses (204 No Content, etc.) - const text = await response.text(); - const data = text ? JSON.parse(text) : []; - - if (!response.ok) { - return NextResponse.json(data, { status: response.status }); - } - - return NextResponse.json(data, { status: response.status }); + const { status, data } = await apiClient(request, "/api/v1/collections/"); + return NextResponse.json(data, { status }); } catch (error: unknown) { return NextResponse.json( - { success: false, error: error instanceof Error ? error.message : String(error), data: null }, - { status: 500 } + { + success: false, + error: error instanceof Error ? error.message : String(error), + data: null, + }, + { status: 500 }, ); } } export async function POST(request: NextRequest) { try { - // Get the API key from request headers - const apiKey = request.headers.get('X-API-KEY'); - - if (!apiKey) { - return NextResponse.json( - { error: 'Missing X-API-KEY header' }, - { status: 401 } - ); - } - // Get the JSON body from the request const body = await request.json(); - // Get backend URL from environment variable - const backendUrl = process.env.BACKEND_URL || 'http://localhost:8000'; - - // Forward the request to the actual backend - const response = await fetch(`${backendUrl}/api/v1/collections/`, { - method: 'POST', + const { status, data } = await apiClient(request, "/api/v1/collections/", { + method: "POST", body: JSON.stringify(body), - headers: { - 'X-API-KEY': apiKey, - 'Content-Type': 'application/json', - }, }); - // Handle empty responses (204 No Content, etc.) - const text = await response.text(); - const data = text ? JSON.parse(text) : { success: true }; - - // Return the response with the same status code - if (!response.ok) { - return NextResponse.json(data, { status: response.status }); - } - - return NextResponse.json(data, { status: response.status }); + return NextResponse.json(data, { status }); } catch (error: unknown) { - console.error('Proxy error:', error); + console.error("Proxy error:", error); return NextResponse.json( - { error: 'Failed to forward request to backend', details: error instanceof Error ? error.message : String(error) }, - { status: 500 } + { + error: "Failed to forward request to backend", + details: error instanceof Error ? error.message : String(error), + }, + { status: 500 }, ); } } diff --git a/app/api/configs/[config_id]/route.ts b/app/api/configs/[config_id]/route.ts index 91ea693..0a5c60c 100644 --- a/app/api/configs/[config_id]/route.ts +++ b/app/api/configs/[config_id]/route.ts @@ -1,82 +1,73 @@ -import { NextResponse, NextRequest } from 'next/server'; +import { NextResponse } from "next/server"; +import { apiClient } from "@/app/lib/apiClient"; export async function GET( request: Request, - { params }: { params: Promise<{ config_id: string }> } + { params }: { params: Promise<{ config_id: string }> }, ) { const { config_id } = await params; - const backendUrl = process.env.BACKEND_URL || 'http://localhost:8000'; - const apiKey = request.headers.get('X-API-KEY'); try { - const response = await fetch(`${backendUrl}/api/v1/configs/${config_id}`, { - headers: { - 'X-API-KEY': apiKey || '', - }, - }); - - const data = await response.json(); - return NextResponse.json(data, { status: response.status }); + const { status, data } = await apiClient( + request, + `/api/v1/configs/${config_id}`, + ); + return NextResponse.json(data, { status }); } catch (_error) { return NextResponse.json( - { success: false, error: 'Failed to fetch config', data: null }, - { status: 500 } + { success: false, error: "Failed to fetch config", data: null }, + { status: 500 }, ); } } export async function PATCH( - request: NextRequest, - { params }: { params: Promise<{ config_id: string }> } + request: Request, + { params }: { params: Promise<{ config_id: string }> }, ) { const { config_id } = await params; - const backendUrl = process.env.BACKEND_URL || 'http://localhost:8000'; - const apiKey = request.headers.get('X-API-KEY'); try { const body = await request.json(); - const response = await fetch(`${backendUrl}/api/v1/configs/${config_id}`, { - method: 'PATCH', - headers: { - 'X-API-KEY': apiKey || '', - 'Content-Type': 'application/json', + const { status, data } = await apiClient( + request, + `/api/v1/configs/${config_id}`, + { + method: "PATCH", + body: JSON.stringify(body), }, - body: JSON.stringify(body), - }); + ); - const data = await response.json(); - return NextResponse.json(data, { status: response.status }); + return NextResponse.json(data, { status }); } catch (_error) { return NextResponse.json( - { success: false, error: 'Failed to update config', data: null }, - { status: 500 } + { success: false, error: "Failed to update config", data: null }, + { status: 500 }, ); } } export async function DELETE( request: Request, - { params }: { params: Promise<{ config_id: string }> } + { params }: { params: Promise<{ config_id: string }> }, ) { const { config_id } = await params; - const backendUrl = process.env.BACKEND_URL || 'http://localhost:8000'; - const apiKey = request.headers.get('X-API-KEY'); try { - const response = await fetch(`${backendUrl}/api/v1/configs/${config_id}`, { - method: 'DELETE', - headers: { - 'X-API-KEY': apiKey || '', + const { status, data } = await apiClient( + request, + `/api/v1/configs/${config_id}`, + { + method: "DELETE", }, - }); + ); - const data = await response.json(); - return NextResponse.json(data, { status: response.status }); + return NextResponse.json(data, { status }); } catch (_error) { return NextResponse.json( - { success: false, error: 'Failed to delete config', data: null }, - { status: 500 } + { success: false, error: "Failed to delete config", data: null }, + { status: 500 }, ); } } diff --git a/app/api/configs/[config_id]/versions/[version_number]/route.ts b/app/api/configs/[config_id]/versions/[version_number]/route.ts index f03fe9a..4d89bd0 100644 --- a/app/api/configs/[config_id]/versions/[version_number]/route.ts +++ b/app/api/configs/[config_id]/versions/[version_number]/route.ts @@ -1,58 +1,49 @@ -import { NextResponse } from 'next/server'; +import { NextResponse } from "next/server"; +import { apiClient } from "@/app/lib/apiClient"; export async function GET( request: Request, - { params }: { params: Promise<{ config_id: string; version_number: string }> } + { + params, + }: { params: Promise<{ config_id: string; version_number: string }> }, ) { const { config_id, version_number } = await params; - const backendUrl = process.env.BACKEND_URL || 'http://localhost:8000'; - const apiKey = request.headers.get('X-API-KEY'); try { - const response = await fetch( - `${backendUrl}/api/v1/configs/${config_id}/versions/${version_number}`, - { - headers: { - 'X-API-KEY': apiKey || '', - }, - } + const { status, data } = await apiClient( + request, + `/api/v1/configs/${config_id}/versions/${version_number}`, ); - - const data = await response.json(); - return NextResponse.json(data, { status: response.status }); + return NextResponse.json(data, { status }); } catch (_error) { return NextResponse.json( - { success: false, error: 'Failed to fetch version', data: null }, - { status: 500 } + { success: false, error: "Failed to fetch version", data: null }, + { status: 500 }, ); } } export async function DELETE( request: Request, - { params }: { params: Promise<{ config_id: string; version_number: string }> } + { + params, + }: { params: Promise<{ config_id: string; version_number: string }> }, ) { const { config_id, version_number } = await params; - const backendUrl = process.env.BACKEND_URL || 'http://localhost:8000'; - const apiKey = request.headers.get('X-API-KEY'); try { - const response = await fetch( - `${backendUrl}/api/v1/configs/${config_id}/versions/${version_number}`, + const { status, data } = await apiClient( + request, + `/api/v1/configs/${config_id}/versions/${version_number}`, { - method: 'DELETE', - headers: { - 'X-API-KEY': apiKey || '', - }, - } + method: "DELETE", + }, ); - - const data = await response.json(); - return NextResponse.json(data, { status: response.status }); + return NextResponse.json(data, { status }); } catch (_error) { return NextResponse.json( - { success: false, error: 'Failed to delete version', data: null }, - { status: 500 } + { success: false, error: "Failed to delete version", data: null }, + { status: 500 }, ); } } diff --git a/app/api/configs/[config_id]/versions/route.ts b/app/api/configs/[config_id]/versions/route.ts index f161cb5..9ac697d 100644 --- a/app/api/configs/[config_id]/versions/route.ts +++ b/app/api/configs/[config_id]/versions/route.ts @@ -1,56 +1,49 @@ -import { NextResponse, NextRequest } from 'next/server'; +import { NextResponse } from "next/server"; +import { apiClient } from "@/app/lib/apiClient"; export async function GET( request: Request, - { params }: { params: Promise<{ config_id: string }> } + { params }: { params: Promise<{ config_id: string }> }, ) { const { config_id } = await params; - const backendUrl = process.env.BACKEND_URL || 'http://localhost:8000'; - const apiKey = request.headers.get('X-API-KEY'); try { - const response = await fetch(`${backendUrl}/api/v1/configs/${config_id}/versions`, { - headers: { - 'X-API-KEY': apiKey || '', - }, - }); - - const data = await response.json(); - return NextResponse.json(data, { status: response.status }); + const { status, data } = await apiClient( + request, + `/api/v1/configs/${config_id}/versions`, + ); + return NextResponse.json(data, { status }); } catch (_error) { return NextResponse.json( - { success: false, error: 'Failed to fetch versions', data: null }, - { status: 500 } + { success: false, error: "Failed to fetch versions", data: null }, + { status: 500 }, ); } } export async function POST( - request: NextRequest, - { params }: { params: Promise<{ config_id: string }> } + request: Request, + { params }: { params: Promise<{ config_id: string }> }, ) { const { config_id } = await params; - const backendUrl = process.env.BACKEND_URL || 'http://localhost:8000'; - const apiKey = request.headers.get('X-API-KEY'); try { const body = await request.json(); - const response = await fetch(`${backendUrl}/api/v1/configs/${config_id}/versions`, { - method: 'POST', - headers: { - 'X-API-KEY': apiKey || '', - 'Content-Type': 'application/json', + const { status, data } = await apiClient( + request, + `/api/v1/configs/${config_id}/versions`, + { + method: "POST", + body: JSON.stringify(body), }, - body: JSON.stringify(body), - }); + ); - const data = await response.json(); - return NextResponse.json(data, { status: response.status }); + return NextResponse.json(data, { status }); } catch (_error) { return NextResponse.json( - { success: false, error: 'Failed to create version', data: null }, - { status: 500 } + { success: false, error: "Failed to create version", data: null }, + { status: 500 }, ); } } diff --git a/app/api/configs/route.ts b/app/api/configs/route.ts index 4c0d510..b29a417 100644 --- a/app/api/configs/route.ts +++ b/app/api/configs/route.ts @@ -1,62 +1,39 @@ -import { NextResponse, NextRequest } from 'next/server'; +import { NextResponse } from "next/server"; +import { apiClient } from "@/app/lib/apiClient"; export async function GET(request: Request) { - const backendUrl = process.env.BACKEND_URL || 'http://localhost:8000'; - const apiKey = request.headers.get('X-API-KEY'); - try { - const response = await fetch(`${backendUrl}/api/v1/configs/`, { - headers: { - 'X-API-KEY': apiKey || '', - }, - }); - - const data = await response.json(); - return NextResponse.json(data); + const { status, data } = await apiClient(request, "/api/v1/configs/"); + return NextResponse.json(data, { status }); } catch (error) { return NextResponse.json( - { success: false, error: error.message, data: null }, - { status: 500 } + { + success: false, + error: error instanceof Error ? error.message : String(error), + data: null, + }, + { status: 500 }, ); } } - -export async function POST(request: NextRequest) { +export async function POST(request: Request) { try { - const apiKey = request.headers.get('X-API-KEY'); - if (!apiKey) { - return NextResponse.json({ - error: 'Missing X-API-KEY. Either generate an API Key. Contact Kaapi team for more details' - }, - { - status: 401 - } - - ) - } - const body=await request.json(); - const backendUrl=process.env.BACKEND_URL || 'http://localhost:8000'; + const body = await request.json(); - const response=await fetch(`${backendUrl}/api/v1/configs/`, { - method:'POST', - body:JSON.stringify(body), - headers:{ - 'X-API-KEY':apiKey, - 'Content-Type':'application/json' - }, + const { status, data } = await apiClient(request, "/api/v1/configs/", { + method: "POST", + body: JSON.stringify(body), }); - const data=await response.json(); - return NextResponse.json(data, {status:response.status}) - - - + return NextResponse.json(data, { status }); } catch (error) { - console.error('Proxy error:', error); + console.error("Proxy error:", error); return NextResponse.json( - {error:'Failed to forward request', details:error.message}, - {status:500} + { + error: "Failed to forward request", + details: error instanceof Error ? error.message : String(error), + }, + { status: 500 }, ); } - -} \ No newline at end of file +} diff --git a/app/api/document/[document_id]/route.ts b/app/api/document/[document_id]/route.ts index 74c7ded..0cee046 100644 --- a/app/api/document/[document_id]/route.ts +++ b/app/api/document/[document_id]/route.ts @@ -1,81 +1,53 @@ -import { NextResponse } from 'next/server'; +import { NextResponse } from "next/server"; +import { apiClient } from "@/app/lib/apiClient"; - -export async function GET(request: Request, - { params }: { params: Promise<{ document_id: string }> } +export async function GET( + request: Request, + { params }: { params: Promise<{ document_id: string }> }, ) { - const { document_id } = await params; - const backendUrl = process.env.BACKEND_URL || 'http://localhost:8000'; - const apiKey = request.headers.get('X-API-KEY'); - - if (!apiKey) { - return NextResponse.json( - { error: 'Missing X-API-KEY header' }, - { status: 401 } - ); - } - try { - const response = await fetch(`${backendUrl}/api/v1/documents/${document_id}?include_url=true`, { - headers: { - 'X-API-KEY': apiKey, - }, - }); - - // Handle empty responses (204 No Content, etc.) - const text = await response.text(); - const data = text ? JSON.parse(text) : {}; - - if (!response.ok) { - return NextResponse.json(data, { status: response.status }); - } - - return NextResponse.json(data, { status: 200 }); + const { status, data } = await apiClient( + request, + `/api/v1/documents/${document_id}?include_url=true`, + ); + return NextResponse.json(data, { status }); } catch (error: unknown) { return NextResponse.json( - { success: false, error: error instanceof Error ? error.message : String(error), data: null }, - { status: 500 } + { + success: false, + error: error instanceof Error ? error.message : String(error), + data: null, + }, + { status: 500 }, ); } } -export async function DELETE(request: Request, - { params }: { params: Promise<{ document_id: string }> } +export async function DELETE( + request: Request, + { params }: { params: Promise<{ document_id: string }> }, ) { const { document_id } = await params; - const backendUrl = process.env.BACKEND_URL || 'http://localhost:8000'; - const apiKey = request.headers.get('X-API-KEY'); - - if (!apiKey) { - return NextResponse.json( - { error: 'Missing X-API-KEY header' }, - { status: 401 } - ); - } try { - const response = await fetch(`${backendUrl}/api/v1/documents/${document_id}`, { - method: 'DELETE', - headers: { - 'X-API-KEY': apiKey, + const { status, data } = await apiClient( + request, + `/api/v1/documents/${document_id}`, + { + method: "DELETE", }, - }); - - // Handle empty responses (204 No Content, etc.) - const text = await response.text(); - const data = text ? JSON.parse(text) : { success: true }; - - if (!response.ok) { - return NextResponse.json(data, { status: response.status }); - } + ); - return NextResponse.json(data, { status: 200 }); + return NextResponse.json(data, { status }); } catch (error: unknown) { - console.error('Delete error:', error); + console.error("Delete error:", error); return NextResponse.json( - { error: 'Failed to delete document', details: error instanceof Error ? error.message : String(error) }, - { status: 500 } + { + error: "Failed to delete document", + details: error instanceof Error ? error.message : String(error), + }, + { status: 500 }, ); } } diff --git a/app/api/document/route.ts b/app/api/document/route.ts index c8c90c9..f9422be 100644 --- a/app/api/document/route.ts +++ b/app/api/document/route.ts @@ -1,84 +1,40 @@ -import { NextRequest, NextResponse } from 'next/server'; - +import { NextRequest, NextResponse } from "next/server"; +import { apiClient } from "@/app/lib/apiClient"; export async function GET(request: Request) { - const backendUrl = process.env.BACKEND_URL || 'http://localhost:8000'; - const apiKey = request.headers.get('X-API-KEY'); - - if (!apiKey) { - return NextResponse.json( - { error: 'Missing X-API-KEY header' }, - { status: 401 } - ); - } - try { - const response = await fetch(`${backendUrl}/api/v1/documents/`, { - headers: { - 'X-API-KEY': apiKey, - }, - }); - - // Handle empty responses (204 No Content, etc.) - const text = await response.text(); - const data = text ? JSON.parse(text) : []; - - if (!response.ok) { - return NextResponse.json(data, { status: response.status }); - } - - return NextResponse.json(data, { status: response.status }); + const { status, data } = await apiClient(request, "/api/v1/documents/"); + return NextResponse.json(data, { status }); } catch (error: unknown) { return NextResponse.json( - { success: false, error: error instanceof Error ? error.message : String(error), data: null }, - { status: 500 } + { + success: false, + error: error instanceof Error ? error.message : String(error), + data: null, + }, + { status: 500 }, ); } } export async function POST(request: NextRequest) { try { - // Get the API key from request headers - const apiKey = request.headers.get('X-API-KEY'); - - if (!apiKey) { - return NextResponse.json( - { error: 'Missing X-API-KEY header' }, - { status: 401 } - ); - } - - // Get the form data from the request const formData = await request.formData(); - // Get backend URL from environment variable - const backendUrl = process.env.BACKEND_URL || 'http://localhost:8000'; - - // Forward the request to the actual backend - const response = await fetch(`${backendUrl}/api/v1/documents/`, { - method: 'POST', + const { status, data } = await apiClient(request, "/api/v1/documents/", { + method: "POST", body: formData, - headers: { - 'X-API-KEY': apiKey, - - }, }); - // Handle empty responses (204 No Content, etc.) - const text = await response.text(); - const data = text ? JSON.parse(text) : { success: true }; - - // Return the response with the same status code - if (!response.ok) { - return NextResponse.json(data, { status: response.status }); - } - - return NextResponse.json(data, { status: response.status }); + return NextResponse.json(data, { status }); } catch (error: unknown) { - console.error('Proxy error:', error); + console.error("Proxy error:", error); return NextResponse.json( - { error: 'Failed to forward request to backend', details: error instanceof Error ? error.message : String(error) }, - { status: 500 } + { + error: "Failed to forward request to backend", + details: error instanceof Error ? error.message : String(error), + }, + { status: 500 }, ); } } diff --git a/app/api/evaluations/[id]/route.ts b/app/api/evaluations/[id]/route.ts index 405ce92..2ec03b8 100644 --- a/app/api/evaluations/[id]/route.ts +++ b/app/api/evaluations/[id]/route.ts @@ -1,9 +1,5 @@ -import { NextRequest, NextResponse } from 'next/server'; -import fs from 'fs'; -import path from 'path'; - -// Set to true to use mock data, false to use real backend -const USE_MOCK_DATA = false; +import { NextRequest, NextResponse } from "next/server"; +import { apiClient } from "@/app/lib/apiClient"; /** * GET /api/evaluations/[id] @@ -11,88 +7,45 @@ const USE_MOCK_DATA = false; */ export async function GET( request: NextRequest, - { params }: { params: Promise<{ id: string }> } + { params }: { params: Promise<{ id: string }> }, ) { try { - const apiKey = request.headers.get('X-API-KEY'); - if (!apiKey) { - return NextResponse.json({ error: 'Missing X-API-KEY' }, { status: 401 }); - } - const { id } = await params; - // Mock data mode - if (USE_MOCK_DATA) { - try { - // Map IDs to mock files - let mockFileName = 'evaluation-sample-1.json'; - if (id === '44' || id === '2') { - mockFileName = 'evaluation-sample-2.json'; - } else if (id === '10' || id === '3') { - // Use the new schema for ID 10 (from the JSON) or ID 3 - mockFileName = 'evaluation-sample-3.json'; - } - - const filePath = path.join(process.cwd(), 'public', 'mock-data', mockFileName); - const fileContent = fs.readFileSync(filePath, 'utf-8'); - const mockData = JSON.parse(fileContent); - - return NextResponse.json(mockData, { status: 200 }); - } catch (err) { - console.error('Error reading mock data:', err); - return NextResponse.json( - { error: 'Mock data not found', details: err.message }, - { status: 404 } - ); - } - } - - // Real backend mode - const backendUrl = process.env.BACKEND_URL || 'http://localhost:8000'; - const searchParams = request.nextUrl.searchParams; - const exportFormat = searchParams.get('export_format') || 'row'; - const resyncScore = searchParams.get('resync_score') || 'false'; + const exportFormat = searchParams.get("export_format") || "row"; + const resyncScore = searchParams.get("resync_score") || "false"; - // Build URL with query parameters - const url = new URL(`${backendUrl}/api/v1/evaluations/${id}`); - url.searchParams.set('get_trace_info', 'true'); - url.searchParams.set('resync_score', resyncScore); - url.searchParams.set('export_format', exportFormat); + const queryParams = new URLSearchParams(); + queryParams.set("get_trace_info", "true"); + queryParams.set("resync_score", resyncScore); + queryParams.set("export_format", exportFormat); - const response = await fetch(url.toString(), { - method: 'GET', - headers: { - 'X-API-KEY': apiKey, - }, - }); + const { status, data } = await apiClient( + request, + `/api/v1/evaluations/${id}?${queryParams.toString()}`, + ); - if (!response.ok) { - const errorText = await response.text(); - console.error(`[REAL BACKEND] Error response: ${errorText}`); - return NextResponse.json( - { error: `Backend error: ${response.statusText}`, details: errorText }, - { status: response.status } - ); + if (status < 200 || status >= 300) { + return NextResponse.json(data ?? { error: "Backend error" }, { status }); } - const data = await response.json(); - - // Validate that we received valid data - if (!data || typeof data !== 'object') { - console.error('[REAL BACKEND] Invalid response format'); + if (!data || typeof data !== "object") { return NextResponse.json( - { error: 'Invalid response format from backend' }, - { status: 500 } + { error: "Invalid response format from backend" }, + { status: 500 }, ); } return NextResponse.json(data, { status: 200 }); } catch (error: unknown) { - console.error('Proxy error:', error); + console.error("Proxy error:", error); return NextResponse.json( - { error: 'Failed to fetch evaluation', details: error instanceof Error ? error.message : String(error) }, - { status: 500 } + { + error: "Failed to fetch evaluation", + details: error instanceof Error ? error.message : String(error), + }, + { status: 500 }, ); } } diff --git a/app/api/evaluations/datasets/[dataset_id]/route.ts b/app/api/evaluations/datasets/[dataset_id]/route.ts index 3c633b9..00561cc 100644 --- a/app/api/evaluations/datasets/[dataset_id]/route.ts +++ b/app/api/evaluations/datasets/[dataset_id]/route.ts @@ -1,4 +1,5 @@ -import { NextRequest, NextResponse } from 'next/server'; +import { NextRequest, NextResponse } from "next/server"; +import { apiClient } from "@/app/lib/apiClient"; /** * GET /api/evaluations/datasets/:dataset_id @@ -7,50 +8,55 @@ import { NextRequest, NextResponse } from 'next/server'; */ export async function GET( request: NextRequest, - { params }: { params: Promise<{ dataset_id: string }> } + { params }: { params: Promise<{ dataset_id: string }> }, ) { try { - const apiKey = request.headers.get('X-API-KEY'); - if (!apiKey) { - return NextResponse.json({ error: 'Missing X-API-KEY header' }, { status: 401 }); - } - const { dataset_id } = await params; - const backendUrl = process.env.BACKEND_URL || 'http://localhost:8000'; const searchParams = request.nextUrl.searchParams.toString(); - const queryString = searchParams ? `?${searchParams}` : ''; + const queryString = searchParams ? `?${searchParams}` : ""; - const response = await fetch(`${backendUrl}/api/v1/evaluations/datasets/${dataset_id}${queryString}`, { - method: 'GET', - headers: { 'X-API-KEY': apiKey }, - }); + const { status, data } = await apiClient( + request, + `/api/v1/evaluations/datasets/${dataset_id}${queryString}`, + ); - const data = await response.json(); - if (!response.ok) { - return NextResponse.json(data, { status: response.status }); + if (status < 200 || status >= 300) { + return NextResponse.json(data, { status }); } // If fetch_content=true, download the CSV from the signed URL and return it - const fetchContent = request.nextUrl.searchParams.get('fetch_content'); - if (fetchContent === 'true') { + const fetchContent = request.nextUrl.searchParams.get("fetch_content"); + if (fetchContent === "true") { const signedUrl = data?.data?.signed_url || data?.signed_url; if (!signedUrl) { - return NextResponse.json({ error: 'No signed URL available' }, { status: 404 }); + return NextResponse.json( + { error: "No signed URL available" }, + { status: 404 }, + ); } const csvResponse = await fetch(signedUrl); if (!csvResponse.ok) { - return NextResponse.json({ error: 'Failed to fetch CSV file' }, { status: 502 }); + return NextResponse.json( + { error: "Failed to fetch CSV file" }, + { status: 502 }, + ); } const csvText = await csvResponse.text(); - return NextResponse.json({ ...data, csv_content: csvText }, { status: 200 }); + return NextResponse.json( + { ...data, csv_content: csvText }, + { status: 200 }, + ); } return NextResponse.json(data, { status: 200 }); } catch (error: unknown) { - console.error('Proxy error:', error); + console.error("Proxy error:", error); return NextResponse.json( - { error: 'Failed to forward request to backend', details: error instanceof Error ? error.message : String(error) }, - { status: 500 } + { + error: "Failed to forward request to backend", + details: error instanceof Error ? error.message : String(error), + }, + { status: 500 }, ); } } @@ -62,52 +68,32 @@ export async function GET( */ export async function DELETE( request: NextRequest, - { params }: { params: Promise<{ dataset_id: string }> } + { params }: { params: Promise<{ dataset_id: string }> }, ) { try { - // Get the API key from request headers - const apiKey = request.headers.get('X-API-KEY'); - - if (!apiKey) { - return NextResponse.json( - { error: 'Missing X-API-KEY header' }, - { status: 401 } - ); - } - const { dataset_id } = await params; - // Get backend URL from environment variable - const backendUrl = process.env.BACKEND_URL || 'http://localhost:8000'; - - // Forward the request to the actual backend - const response = await fetch(`${backendUrl}/api/v1/evaluations/datasets/${dataset_id}`, { - method: 'DELETE', - headers: { - 'X-API-KEY': apiKey, + const { status, data } = await apiClient( + request, + `/api/v1/evaluations/datasets/${dataset_id}`, + { + method: "DELETE", }, - }); - - // Get the response data - let data; - try { - data = await response.json(); - } catch (_e) { - // If response is not JSON, just return success - data = { success: true }; - } + ); - // Return the response with the same status code - if (!response.ok) { - return NextResponse.json(data, { status: response.status }); + if (status < 200 || status >= 300) { + return NextResponse.json(data, { status }); } return NextResponse.json(data, { status: 200 }); } catch (error: unknown) { - console.error('Proxy error:', error); + console.error("Proxy error:", error); return NextResponse.json( - { error: 'Failed to forward request to backend', details: error instanceof Error ? error.message : String(error) }, - { status: 500 } + { + error: "Failed to forward request to backend", + details: error instanceof Error ? error.message : String(error), + }, + { status: 500 }, ); } } diff --git a/app/api/evaluations/datasets/route.ts b/app/api/evaluations/datasets/route.ts index 9ea9b9e..c397e23 100644 --- a/app/api/evaluations/datasets/route.ts +++ b/app/api/evaluations/datasets/route.ts @@ -1,4 +1,5 @@ -import { NextRequest, NextResponse } from 'next/server'; +import { NextRequest, NextResponse } from "next/server"; +import { apiClient } from "@/app/lib/apiClient"; /** * GET /api/evaluations/datasets @@ -7,93 +8,50 @@ import { NextRequest, NextResponse } from 'next/server'; */ export async function GET(request: NextRequest) { try { - // Get the API key from request headers - const apiKey = request.headers.get('X-API-KEY'); - - if (!apiKey) { - return NextResponse.json( - { error: 'Missing X-API-KEY header' }, - { status: 401 } - ); - } - - // Get backend URL from environment variable - const backendUrl = process.env.BACKEND_URL || 'http://localhost:8000'; - - // Forward the request to the actual backend - const response = await fetch(`${backendUrl}/api/v1/evaluations/datasets`, { - method: 'GET', - headers: { - 'X-API-KEY': apiKey, - }, - }); - - // Get the response data - const data = await response.json(); - - // Return the response with the same status code - if (!response.ok) { - return NextResponse.json(data, { status: response.status }); - } + const { status, data } = await apiClient( + request, + "/api/v1/evaluations/datasets", + ); - return NextResponse.json(data, { status: 200 }); + return NextResponse.json(data, { status }); } catch (error: unknown) { - console.error('Proxy error:', error); + console.error("Proxy error:", error); return NextResponse.json( - { error: 'Failed to forward request to backend', details: error instanceof Error ? error.message : String(error) }, - { status: 500 } + { + error: "Failed to forward request to backend", + details: error instanceof Error ? error.message : String(error), + }, + { status: 500 }, ); } } /** * POST /api/evaluations/datasets - * - * Proxy endpoint to work around CORS issues. - * Forwards multipart/form-data requests to the backend API. + * Forwards multipart/form-data (CSV upload) to the backend. */ export async function POST(request: NextRequest) { try { - // Get the API key from request headers - const apiKey = request.headers.get('X-API-KEY'); - - if (!apiKey) { - return NextResponse.json( - { error: 'Missing X-API-KEY header' }, - { status: 401 } - ); - } - - // Get the form data from the request const formData = await request.formData(); - // Get backend URL from environment variable - const backendUrl = process.env.BACKEND_URL || 'http://localhost:8000'; - - // Forward the request to the actual backend - const response = await fetch(`${backendUrl}/api/v1/evaluations/datasets`, { - method: 'POST', - body: formData, - headers: { - 'X-API-KEY': apiKey, - + const { status, data } = await apiClient( + request, + "/api/v1/evaluations/datasets", + { + method: "POST", + body: formData, }, - }); - - // Get the response data - const data = await response.json(); - - // Return the response with the same status code - if (!response.ok) { - return NextResponse.json(data, { status: response.status }); - } + ); - return NextResponse.json(data, { status: 200 }); + return NextResponse.json(data, { status }); } catch (error: unknown) { - console.error('Proxy error:', error); + console.error("Proxy error:", error); return NextResponse.json( - { error: 'Failed to forward request to backend', details: error instanceof Error ? error.message : String(error) }, - { status: 500 } + { + error: "Failed to forward request to backend", + details: error instanceof Error ? error.message : String(error), + }, + { status: 500 }, ); } } diff --git a/app/api/evaluations/route.ts b/app/api/evaluations/route.ts index 2ca8bb7..c626844 100644 --- a/app/api/evaluations/route.ts +++ b/app/api/evaluations/route.ts @@ -1,4 +1,5 @@ -import { NextRequest, NextResponse } from 'next/server'; +import { NextRequest, NextResponse } from "next/server"; +import { apiClient } from "@/app/lib/apiClient"; /** * GET /api/evaluations @@ -6,28 +7,17 @@ import { NextRequest, NextResponse } from 'next/server'; */ export async function GET(request: NextRequest) { try { - const apiKey = request.headers.get('X-API-KEY'); - if (!apiKey) { - return NextResponse.json({ error: 'Missing X-API-KEY' }, { status: 401 }); - } + const { status, data } = await apiClient(request, "/api/v1/evaluations"); - const backendUrl = process.env.BACKEND_URL || 'http://localhost:8000'; - - const response = await fetch(`${backendUrl}/api/v1/evaluations`, { - method: 'GET', - headers: { - 'X-API-KEY': apiKey, - }, - }); - - const data = await response.json(); - - return NextResponse.json(data, { status: response.status }); + return NextResponse.json(data, { status }); } catch (error) { - console.error('Proxy error:', error); + console.error("Proxy error:", error); return NextResponse.json( - { error: 'Failed to fetch evaluations', details: error.message }, - { status: 500 } + { + error: "Failed to fetch evaluations", + details: error instanceof Error ? error.message : String(error), + }, + { status: 500 }, ); } } @@ -38,30 +28,22 @@ export async function GET(request: NextRequest) { */ export async function POST(request: NextRequest) { try { - const apiKey = request.headers.get('X-API-KEY'); - if (!apiKey) { - return NextResponse.json({ error: 'Missing X-API-KEY' }, { status: 401 }); - } - const body = await request.json(); - const backendUrl = process.env.BACKEND_URL || 'http://localhost:8000'; - const response = await fetch(`${backendUrl}/api/v1/evaluations`, { - method: 'POST', + const { status, data } = await apiClient(request, "/api/v1/evaluations", { + method: "POST", body: JSON.stringify(body), - headers: { - 'X-API-KEY': apiKey, - 'Content-Type': 'application/json', - }, }); - const data = await response.json(); - return NextResponse.json(data, { status: response.status }); + return NextResponse.json(data, { status }); } catch (error) { - console.error('Proxy error:', error); + console.error("Proxy error:", error); return NextResponse.json( - { error: 'Failed to forward request', details: error.message }, - { status: 500 } + { + error: "Failed to forward request", + details: error instanceof Error ? error.message : String(error), + }, + { status: 500 }, ); } -} \ No newline at end of file +} diff --git a/app/api/evaluations/stt/datasets/[dataset_id]/route.ts b/app/api/evaluations/stt/datasets/[dataset_id]/route.ts index 5f085ba..5b80691 100644 --- a/app/api/evaluations/stt/datasets/[dataset_id]/route.ts +++ b/app/api/evaluations/stt/datasets/[dataset_id]/route.ts @@ -1,20 +1,11 @@ -import { NextResponse } from 'next/server'; +import { NextResponse } from "next/server"; +import { apiClient } from "@/app/lib/apiClient"; export async function GET( request: Request, - { params }: { params: Promise<{ dataset_id: string }> } + { params }: { params: Promise<{ dataset_id: string }> }, ) { const { dataset_id } = await params; - const backendUrl = process.env.BACKEND_URL || 'http://localhost:8000'; - const apiKey = request.headers.get('X-API-KEY'); - - if (!apiKey) { - return NextResponse.json( - { success: false, error: 'Unauthorized: Missing API key', data: null }, - { status: 401 } - ); - } - try { // Forward all query parameters to the backend const { searchParams } = new URL(request.url); @@ -22,47 +13,47 @@ export async function GET( for (const [key, value] of searchParams.entries()) { backendParams.append(key, value); } - const queryString = backendParams.toString() ? `?${backendParams.toString()}` : ''; + const queryString = backendParams.toString() + ? `?${backendParams.toString()}` + : ""; - const backendUrlWithParams = `${backendUrl}/api/v1/evaluations/stt/datasets/${dataset_id}${queryString}`; - - const response = await fetch(backendUrlWithParams, { - headers: { - 'X-API-KEY': apiKey, - }, - }); - - const data = await response.json(); - return NextResponse.json(data, { status: response.status }); + const { status, data } = await apiClient( + request, + `/api/v1/evaluations/stt/datasets/${dataset_id}${queryString}`, + ); + return NextResponse.json(data, { status }); } catch (_error) { return NextResponse.json( - { success: false, error: 'Failed to fetch dataset', data: null }, - { status: 500 } + { success: false, error: "Failed to fetch dataset", data: null }, + { status: 500 }, ); } } export async function DELETE( request: Request, - { params }: { params: Promise<{ dataset_id: string }> } + { params }: { params: Promise<{ dataset_id: string }> }, ) { const { dataset_id } = await params; - const backendUrl = process.env.BACKEND_URL || 'http://localhost:8000'; - const apiKey = request.headers.get('X-API-KEY'); - - if (!apiKey) { - return NextResponse.json({ success: false, error: 'Unauthorized: Missing API key' }, { status: 401 }); - } - try { - const response = await fetch(`${backendUrl}/api/v1/evaluations/stt/datasets/${dataset_id}`, { - method: 'DELETE', - headers: { 'X-API-KEY': apiKey }, + const { status, data } = await apiClient( + request, + `/api/v1/evaluations/stt/datasets/${dataset_id}`, + { + method: "DELETE", + }, + ); + return NextResponse.json(data, { + status: status >= 200 && status < 300 ? 200 : status, }); - let data; - try { data = await response.json(); } catch { data = { success: true }; } - return NextResponse.json(data, { status: response.ok ? 200 : response.status }); } catch (error: unknown) { - return NextResponse.json({ success: false, error: 'Failed to delete dataset', details: error instanceof Error ? error.message : String(error) }, { status: 500 }); + return NextResponse.json( + { + success: false, + error: "Failed to delete dataset", + details: error instanceof Error ? error.message : String(error), + }, + { status: 500 }, + ); } -} \ No newline at end of file +} diff --git a/app/api/evaluations/stt/datasets/route.ts b/app/api/evaluations/stt/datasets/route.ts index abc30c5..d8682e1 100644 --- a/app/api/evaluations/stt/datasets/route.ts +++ b/app/api/evaluations/stt/datasets/route.ts @@ -1,65 +1,42 @@ -import { NextResponse, NextRequest } from 'next/server'; - - - -export async function GET(request: - Request) { - const backendUrl = process.env.BACKEND_URL || 'http://localhost:8000'; - const apiKey = request.headers.get('X-API-KEY'); +import { NextResponse } from "next/server"; +import { apiClient } from "@/app/lib/apiClient"; +export async function GET(request: Request) { try { - const response = await fetch(`${backendUrl}/api/v1/evaluations/stt/datasets`, { - headers: { - 'X-API-KEY': apiKey || '', - }, - }); - - const data = await response.json(); - return NextResponse.json(data, { status: response.status }); + const { status, data } = await apiClient( + request, + "/api/v1/evaluations/stt/datasets", + ); + return NextResponse.json(data, { status }); } catch (error) { return NextResponse.json( { success: false, error: error, data: null }, - { status: 500 } + { status: 500 }, ); } } - -export async function POST(request: NextRequest) { +export async function POST(request: Request) { try { - const apiKey = request.headers.get('X-API-KEY'); - if (!apiKey) { - return NextResponse.json({ - error: 'Missing X-API-KEY. Either generate an API Key. Contact Kaapi team for more details' + const body = await request.json(); + + const { status, data } = await apiClient( + request, + "/api/v1/evaluations/stt/datasets", + { + method: "POST", + body: JSON.stringify(body), }, - { - status: 401 - } - - ) - } - const body=await request.json(); - const backendUrl=process.env.BACKEND_URL || 'http://localhost:8000'; - - const response=await fetch(`${backendUrl}/api/v1/evaluations/stt/datasets`, { - method:'POST', - body:JSON.stringify(body), - headers:{ - 'X-API-KEY':apiKey, - 'Content-Type':'application/json' - }, - }); - const data=await response.json(); - return NextResponse.json(data, {status:response.status}) - - - + ); + return NextResponse.json(data, { status }); } catch (error) { - console.error('Proxy error:', error); + console.error("Proxy error:", error); return NextResponse.json( - {error: 'Failed to forward request to backend', details: error instanceof Error ? error.message : String(error)}, - {status:500} + { + error: "Failed to forward request to backend", + details: error instanceof Error ? error.message : String(error), + }, + { status: 500 }, ); } - -} \ No newline at end of file +} diff --git a/app/api/evaluations/stt/results/[result_id]/route.ts b/app/api/evaluations/stt/results/[result_id]/route.ts index a336c1c..9b564f2 100644 --- a/app/api/evaluations/stt/results/[result_id]/route.ts +++ b/app/api/evaluations/stt/results/[result_id]/route.ts @@ -1,64 +1,48 @@ -import { NextResponse } from 'next/server'; +import { NextResponse } from "next/server"; +import { apiClient } from "@/app/lib/apiClient"; export async function GET( request: Request, - { params }: { params: Promise<{ result_id: string }> } + { params }: { params: Promise<{ result_id: string }> }, ) { const { result_id } = await params; - const backendUrl = process.env.BACKEND_URL || 'http://localhost:8000'; - const apiKey = request.headers.get('X-API-KEY'); try { - const response = await fetch(`${backendUrl}/api/v1/evaluations/stt/results/${result_id}`, { - headers: { - 'X-API-KEY': apiKey || '', - }, - }); - - const data = await response.json(); - return NextResponse.json(data, { status: response.status }); + const { status, data } = await apiClient( + request, + `/api/v1/evaluations/stt/results/${result_id}`, + ); + return NextResponse.json(data, { status }); } catch (_error) { return NextResponse.json( - { success: false, error: 'Failed to fetch results', data: null }, - { status: 500 } + { success: false, error: "Failed to fetch results", data: null }, + { status: 500 }, ); } } - export async function PATCH( request: Request, - { params }: { params: Promise<{ result_id: string }> } + { params }: { params: Promise<{ result_id: string }> }, ) { const { result_id } = await params; - const backendUrl = process.env.BACKEND_URL || 'http://localhost:8000'; - const apiKey = request.headers.get('X-API-KEY'); - - if (!apiKey) { - return NextResponse.json( - { error: 'Missing X-API-KEY header' }, - { status: 401 } - ); - } - try { const body = await request.json(); - const response = await fetch(`${backendUrl}/api/v1/evaluations/stt/results/${result_id}`, { - method: 'PATCH', - headers: { - 'X-API-KEY': apiKey || '', - 'Content-Type': 'application/json', + const { status, data } = await apiClient( + request, + `/api/v1/evaluations/stt/results/${result_id}`, + { + method: "PATCH", + body: JSON.stringify(body), }, - body: JSON.stringify(body), - }); + ); - const data = await response.json(); - return NextResponse.json(data, { status: response.status }); + return NextResponse.json(data, { status }); } catch (_error) { return NextResponse.json( - { success: false, error: 'Failed to update result feedback', data: null }, - { status: 500 } + { success: false, error: "Failed to update result feedback", data: null }, + { status: 500 }, ); } -} \ No newline at end of file +} diff --git a/app/api/evaluations/stt/runs/[run_id]/route.ts b/app/api/evaluations/stt/runs/[run_id]/route.ts index 3aab95d..cb960c3 100644 --- a/app/api/evaluations/stt/runs/[run_id]/route.ts +++ b/app/api/evaluations/stt/runs/[run_id]/route.ts @@ -1,12 +1,11 @@ -import { NextResponse } from 'next/server'; +import { NextResponse } from "next/server"; +import { apiClient } from "@/app/lib/apiClient"; export async function GET( request: Request, - { params }: { params: Promise<{ run_id: string }> } + { params }: { params: Promise<{ run_id: string }> }, ) { const { run_id } = await params; - const backendUrl = process.env.BACKEND_URL || 'http://localhost:8000'; - const apiKey = request.headers.get('X-API-KEY'); // Extract query parameters from the request URL const { searchParams } = new URL(request.url); @@ -14,22 +13,16 @@ export async function GET( try { // Forward query parameters to the backend - const backendUrlWithParams = queryString - ? `${backendUrl}/api/v1/evaluations/stt/runs/${run_id}?${queryString}` - : `${backendUrl}/api/v1/evaluations/stt/runs/${run_id}`; + const endpoint = queryString + ? `/api/v1/evaluations/stt/runs/${run_id}?${queryString}` + : `/api/v1/evaluations/stt/runs/${run_id}`; - const response = await fetch(backendUrlWithParams, { - headers: { - 'X-API-KEY': apiKey || '', - }, - }); - - const data = await response.json(); - return NextResponse.json(data, { status: response.status }); + const { status, data } = await apiClient(request, endpoint); + return NextResponse.json(data, { status }); } catch (_error) { return NextResponse.json( - { success: false, error: 'Failed to fetch the run', data: null }, - { status: 500 } + { success: false, error: "Failed to fetch the run", data: null }, + { status: 500 }, ); } -} \ No newline at end of file +} diff --git a/app/api/evaluations/stt/runs/route.ts b/app/api/evaluations/stt/runs/route.ts index e37b629..1c21d4b 100644 --- a/app/api/evaluations/stt/runs/route.ts +++ b/app/api/evaluations/stt/runs/route.ts @@ -1,64 +1,52 @@ -import { NextResponse, NextRequest } from 'next/server'; - - +import { NextResponse } from "next/server"; +import { apiClient } from "@/app/lib/apiClient"; export async function GET(request: Request) { - const backendUrl = process.env.BACKEND_URL || 'http://localhost:8000'; - const apiKey = request.headers.get('X-API-KEY'); - try { - const response = await fetch(`${backendUrl}/api/v1/evaluations/stt/runs`, { - headers: { - 'X-API-KEY': apiKey || '', - }, - }); - - const data = await response.json(); - return NextResponse.json(data, { status: response.status }); + const { status, data } = await apiClient( + request, + "/api/v1/evaluations/stt/runs", + ); + return NextResponse.json(data, { status }); } catch (error) { return NextResponse.json( { success: false, error: error, data: null }, - { status: 500 } + { status: 500 }, ); } } - -export async function POST(request: NextRequest) { +export async function POST(request: Request) { try { - const apiKey = request.headers.get('X-API-KEY'); + const apiKey = request.headers.get("X-API-KEY"); if (!apiKey) { - return NextResponse.json({ - error: 'Missing X-API-KEY. Either generate an API Key. Contact Kaapi team for more details' - }, + return NextResponse.json( { - status: 401 - } - - ) + error: + "Missing X-API-KEY. Either generate an API Key. Contact Kaapi team for more details", + }, + { status: 401 }, + ); } - const body=await request.json(); - const backendUrl=process.env.BACKEND_URL || 'http://localhost:8000'; - - const response=await fetch(`${backendUrl}/api/v1/evaluations/stt/runs`, { - method:'POST', - body:JSON.stringify(body), - headers:{ - 'X-API-KEY':apiKey, - 'Content-Type':'application/json' + const body = await request.json(); + + const { status, data } = await apiClient( + request, + "/api/v1/evaluations/stt/runs", + { + method: "POST", + body: JSON.stringify(body), }, - }); - const data=await response.json(); - return NextResponse.json(data, {status:response.status}) - - - + ); + return NextResponse.json(data, { status }); } catch (error) { - console.error('Proxy error:', error); + console.error("Proxy error:", error); return NextResponse.json( - {error: 'Failed to forward request to backend', details: error instanceof Error ? error.message : String(error)}, - {status:500} + { + error: "Failed to forward request to backend", + details: error instanceof Error ? error.message : String(error), + }, + { status: 500 }, ); } - -} \ No newline at end of file +} diff --git a/app/api/evaluations/stt/samples/[sample_id]/route.ts b/app/api/evaluations/stt/samples/[sample_id]/route.ts index bf4cbea..053e78a 100644 --- a/app/api/evaluations/stt/samples/[sample_id]/route.ts +++ b/app/api/evaluations/stt/samples/[sample_id]/route.ts @@ -1,47 +1,33 @@ -import { NextResponse } from 'next/server'; +import { NextResponse } from "next/server"; +import { apiClient } from "@/app/lib/apiClient"; export async function PATCH( request: Request, - { params }: { params: Promise<{ sample_id: string }> } + { params }: { params: Promise<{ sample_id: string }> }, ) { const { sample_id } = await params; - const backendUrl = process.env.BACKEND_URL || 'http://localhost:8000'; - const apiKey = request.headers.get('X-API-KEY'); - - if (!apiKey) { - return NextResponse.json( - { success: false, error: 'Unauthorized: Missing API key' }, - { status: 401 } - ); - } - try { const body = await request.json(); - const response = await fetch( - `${backendUrl}/api/v1/evaluations/stt/samples/${sample_id}`, + const { status, data } = await apiClient( + request, + `/api/v1/evaluations/stt/samples/${sample_id}`, { - method: 'PATCH', - headers: { - 'X-API-KEY': apiKey, - 'Content-Type': 'application/json', - }, + method: "PATCH", body: JSON.stringify(body), - } + }, ); - let data; - try { - data = await response.json(); - } catch { - data = { success: response.ok }; - } - return NextResponse.json(data, { status: response.status }); + return NextResponse.json(data, { status }); } catch (error: unknown) { - console.error('Sample update error:', error); + console.error("Sample update error:", error); return NextResponse.json( - { success: false, error: 'Failed to update sample', details: error instanceof Error ? error.message : String(error) }, - { status: 500 } + { + success: false, + error: "Failed to update sample", + details: error instanceof Error ? error.message : String(error), + }, + { status: 500 }, ); } } diff --git a/app/lib/apiClient.ts b/app/lib/apiClient.ts index 7d78323..3895f4e 100644 --- a/app/lib/apiClient.ts +++ b/app/lib/apiClient.ts @@ -1,7 +1,6 @@ import { NextRequest } from "next/server"; -const BACKEND_URL = - process.env.BACKEND_URL || "http://localhost:8000"; +const BACKEND_URL = process.env.BACKEND_URL || "http://localhost:8000"; /** * Passthrough proxy helper for Next.js route handlers. @@ -15,7 +14,10 @@ export async function apiClient( ) { const apiKey = request.headers.get("X-API-KEY") || ""; const headers = new Headers(options.headers); - headers.set("Content-Type", "application/json"); + // Don't set Content-Type for FormData — the browser sets it with the boundary + if (!(options.body instanceof FormData)) { + headers.set("Content-Type", "application/json"); + } headers.set("X-API-KEY", apiKey); const response = await fetch(`${BACKEND_URL}${endpoint}`, { @@ -24,7 +26,8 @@ export async function apiClient( }); // 204 No Content has no body - const data = response.status === 204 ? null : await response.json(); + const text = response.status === 204 ? "" : await response.text(); + const data = text ? JSON.parse(text) : null; return { status: response.status, data }; }