Cache iTunes request

This commit is contained in:
An Phan 2016-12-11 21:21:45 +08:00
parent 86ca8d40f6
commit 876db46501
No known key found for this signature in database
GPG key ID: 05536BB4BCDC02A2
2 changed files with 35 additions and 20 deletions

View file

@ -2,7 +2,9 @@
namespace App\Services;
use Exception;
use GuzzleHttp\Client;
use Log;
class iTunes
{
@ -47,29 +49,40 @@ class iTunes
*/
public function getTrackUrl($term, $album = '', $artist = '')
{
$params = [
'term' => $term.($album ? ' '.$album : '').($artist ? ' '.$artist : ''),
'media' => 'music',
'entity' => 'song',
'limit' => 1,
];
try {
$cacheKey = md5("itunes_track_url_{$term}{$album}{$artist}");
if (!$trackUrl = cache($cacheKey)) {
$params = [
'term' => $term.($album ? ' '.$album : '').($artist ? ' '.$artist : ''),
'media' => 'music',
'entity' => 'song',
'limit' => 1,
];
$response = (string) $this->client->get($this->endPoint, ['query' => $params])->getBody();
$response = json_decode($response);
$response = (string) $this->client->get($this->endPoint, ['query' => $params])->getBody();
$response = json_decode($response);
if (!$response->resultCount) {
return false;
}
$trackUrl = $response->results[0]->trackViewUrl;
// Returns a string if the URL has parameters or NULL if not
if (parse_url($trackUrl, PHP_URL_QUERY)) {
$trackUrl .= '&at='.config('koel.itunes.affiliate_id');
} else {
$trackUrl .= '?at='.config('koel.itunes.affiliate_id');
}
cache([$cacheKey => $trackUrl], 24 * 60 * 7);
}
return $trackUrl;
} catch (Exception $e) {
Log::error($e);
if (!$response->resultCount) {
return false;
}
$trackUrl = $response->results[0]->trackViewUrl;
// Returns a string if the URL has parameters or NULL if not
if (parse_url($trackUrl, PHP_URL_QUERY)) {
$trackUrl .= '&at='.config('koel.itunes.affiliate_id');
} else {
$trackUrl .= '?at='.config('koel.itunes.affiliate_id');
}
return $trackUrl;
}
}

View file

@ -21,5 +21,7 @@ class iTunesTest extends TestCase
'https://itunes.apple.com/us/album/i-remember-you/id265611220?i=265611396&uo=4&at=1000lsGu',
$api->getTrackUrl('Foo Bar')
);
self::assertNotNull(cache(md5('itunes_track_url_Foo Bar')));
}
}