1+ <?php
2+
3+ namespace Controllers ;
4+
5+ use Spatie \RouteAttributes \Attributes \Any ;
6+ use Illuminate \Support \Facades \Auth ;
7+ use Illuminate \Http \Request ;
8+
9+ use GuzzleHttp \Client ;
10+ use GuzzleHttp \Exception \RequestException ;
11+ use Illuminate \Http \JsonResponse ;
12+ use Spatie \RouteAttributes \Attributes \Where ;
13+
14+ class APIForUIController extends PageController
15+ {
16+ #[Any('/api-for-ui/{path} ' )]
17+ #[Where('path ' , '(.*) ' )]
18+ public function __invoke (Request $ request , string $ path = null )
19+ {
20+ $ tokens = Auth::user ()->getApiTokens ();
21+
22+ // Determine actual API path
23+ $ url = str_replace ("api-for-ui/ " , "" ,$ request ->fullUrl ());
24+
25+ // Create a new Guzzle client
26+ $ client = new Client ();
27+
28+ // Get headers from the incoming request
29+ $ incomingHeaders = $ request ->headers ->all ();
30+
31+ // Format headers for Guzzle
32+ $ formattedHeaders = [];
33+ foreach ($ incomingHeaders as $ key => $ value ) {
34+ $ formattedHeaders [$ key ] = implode (', ' , $ value ); // Convert array to string
35+ }
36+
37+ // Attach API token for auth
38+ $ formattedHeaders ['X-API-Key ' ] = $ tokens [0 ]['token ' ];
39+
40+ try {
41+ // Make the GET request
42+ $ response = $ client ->request ($ request ->method (), $ url , [
43+ 'headers ' => $ formattedHeaders ,
44+ 'json ' => $ request ->all (),
45+ ]);
46+
47+ // Get the body of the response
48+ $ body = $ response ->getBody ();
49+ $ data = json_decode ($ body , true ); // Decode JSON to array
50+
51+ // Return the response data
52+ return response ()->json ($ data );
53+ } catch (RequestException $ e ) {
54+ // Handle different types of errors
55+ $ statusCode = $ e ->getResponse () ? $ e ->getResponse ()->getStatusCode () : 500 ;
56+ return response ()->json ([
57+ 'error ' => $ e ->getMessage (),
58+ 'status_code ' => $ statusCode ,
59+ ], $ statusCode );
60+ }
61+ }
62+ }
0 commit comments