Add short timeout to HTTP calls by default; cache METAR lookups

This commit is contained in:
Nabeel Shahzad
2018-05-14 11:20:38 -05:00
parent c8a9ebd26d
commit 3e96b195a6
5 changed files with 34 additions and 8 deletions

View File

@@ -84,13 +84,12 @@ class AirportController extends Controller
{
$airport = Cache::remember(
config('cache.keys.AIRPORT_VACENTRAL_LOOKUP.key').$id,
config('cache.keys.RANKS_PILOT_LIST.time'),
config('cache.keys.AIRPORT_VACENTRAL_LOOKUP.time'),
function () use ($id) {
try {
return AirportLookup::get($id);
} catch (\VaCentral\HttpException $e) {
Log::error($e);
return [];
}
}

View File

@@ -4,6 +4,7 @@ namespace App\Services\Metar;
use App\Interfaces\Metar;
use App\Support\Http;
use Cache;
/**
* Return the raw METAR string from the NOAA Aviation Weather Service
@@ -20,13 +21,25 @@ class AviationWeather extends Metar
* Implement the METAR - Return the string
* @param $icao
* @return string
* @throws \GuzzleHttp\Exception\GuzzleException
*/
protected function metar($icao): string
{
$url = static::METAR_URL.$icao;
$res = Http::get($url, []);
$xml = simplexml_load_string($res);
return $xml->data->METAR->raw_text->__toString();
$metar = Cache::remember(
config('cache.keys.WEATHER_LOOKUP.key').$icao,
config('cache.keys.WEATHER_LOOKUP.time'),
function () use ($icao) {
$url = static::METAR_URL.$icao;
try {
$res = Http::get($url, []);
$xml = simplexml_load_string($res);
return $xml->data->METAR->raw_text->__toString();
} catch (\Exception $e) {
return '';
}
}
);
return $metar;
}
}

View File

@@ -20,6 +20,10 @@ class Http
*/
public static function get($uri, array $opts)
{
$opts = array_merge([
'connect_timeout' => 2, // wait two seconds by default
], $opts);
$client = new Client();
$response = $client->request('GET', $uri, $opts);

View File

@@ -12,7 +12,7 @@ return [
],
'WEATHER_LOOKUP' => [
'key' => 'airports.weather.', // append icao
'time' => 60 * 30, // Cache for 30 minutes
'time' => 60 * 60, // Cache for 60 minutes
],
'RANKS_PILOT_LIST' => [
'key' => 'ranks.pilot_list',

View File

@@ -16,6 +16,16 @@ class MetarTest extends TestCase
$this->settingsRepo = app(SettingRepository::class);
}
/**
* Make sure a blank metar doesn't give problems
*/
public function testBlankMetar()
{
$metar = '';
$parsed = Metar::parse($metar);
$this->assertEquals('', $parsed['raw']);
}
/**
* Test adding/subtracting a percentage
*/