Files
lara-bermite/app/Http/Controllers/WeatherController.php
2023-09-24 11:19:58 +02:00

46 lines
1.6 KiB
PHP

<?php
namespace App\Http\Controllers;
use Exception;
use GuzzleHttp\Client;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;
class WeatherController extends Controller
{
public function index(Request $request): JsonResponse
{
abort_if($request->user()->locations->count() === 0, 404, 'Coordonnées non renseignées dans le profile.');
$location = $request->user()->locations->first();
$idCity = 6427013;
$apiKey = config('weather.open_weather_map_api_key');
try {
$response = Cache::remember('weather-'.$location->id, 5 * 60, function () use ($location, $apiKey) {
// $url = 'https://api.openweathermap.org/data/2.5/forecast?id='.$idCity.'&appid='.$apiKey.$params;
$params = '&units=metric&lang=fr';
$url = 'https://api.openweathermap.org/data/2.5/forecast?lat='.$location->latitude.'&lon='.$location->longitude.'&appid='.$apiKey.$params;
$client = new Client();
$promise = $client->requestAsync('GET', $url);
$response = $promise->wait();
return json_decode($response->getBody()->getContents());
});
return response()->json($response);
} catch (Exception $e) {
Log::alert('unable to fetch data', [
'ip' => $request->ip(),
'code' => $e->getCode(),
'message' => $e->getMessage(),
]);
return response()->json('unable to fetch data', 500);
}
}
}