AI-markdown/laravel-app/app/Http/Controllers/ApiProxyController.php

50 lines
1.7 KiB
PHP

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;
use Spatie\RouteAttributes\Attributes\Any;
use Spatie\RouteAttributes\Attributes\Middleware;
use Spatie\RouteAttributes\Attributes\Where;
#[Middleware('web')]
class ApiProxyController extends Controller
{
private const SERVICES = [
'markitdown' => 'http://api-markitdown:8000',
'docling' => 'http://api-docling:8000',
'unlimited-ocr' => 'http://api-unlimited-ocr:8000',
];
#[Any('/api/{service}/{path?}')]
#[Where('path', '.*')]
public function proxy(Request $request, string $service, string $path = '')
{
$base = self::SERVICES[$service] ?? abort(404, "Unknown service: $service");
$url = rtrim($base, '/') . '/' . ltrim($path, '/');
if ($qs = $request->getQueryString()) {
$url .= '?' . $qs;
}
$http = Http::timeout(300)->withoutVerifying();
if ($request->hasFile('file')) {
$file = $request->file('file');
$response = $http
->attach('file', file_get_contents($file->getRealPath()), $file->getClientOriginalName())
->post($url);
} else {
$contentType = $request->header('Content-Type', 'application/json');
$response = $http
->withHeaders(['Content-Type' => $contentType])
->withBody($request->getContent(), $contentType)
->send($request->method(), $url);
}
return response($response->body(), $response->status())
->header('Content-Type', $response->header('Content-Type', 'application/json'));
}
}