Created
October 10, 2017 14:12
-
-
Save urukalo/cb5215fe7aff1d2eed1b3e8f6957dafb to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App\Http\Middleware; | |
use Cache; | |
use Closure; | |
use Predis\Response\ServerException; | |
class CacheApiMiddleware | |
{ | |
/** | |
* Handle an incoming request. | |
* | |
* @param \Illuminate\Http\Request $request | |
* @param \Closure $next | |
* @return mixed | |
*/ | |
public function handle($request, Closure $next) | |
{ | |
if (($request->is('v1/*') || $request->is('v2/*')) | |
&& $request->isMethod('get') | |
&& env('APP_ENV', 'production') !== 'local' | |
) { | |
//generate key from url and check for cache | |
$key = str_slug($request->fullUrl()); | |
$tags = $request->segments(); | |
if (Cache::tags($tags)->has($key)) { | |
//there is cache, return it | |
return response(Cache::tags($tags)->get($key), 200, ['Content-Type' => 'application/json; charset=utf-8']); | |
} | |
} | |
return $next($request); | |
} | |
public function terminate($request, $response) | |
{ | |
// get cache tags and remove them | |
if (($request->is('v1/*') || $request->is('v2/*')) | |
&& $request->isMethod('get') | |
&& $response->getStatusCode() === 200 | |
&& env('APP_ENV', 'production') !== 'local' | |
) { | |
$key = str_slug($request->fullUrl()); | |
try { | |
Cache::tags($request->segments())->put($key, $response->getContent(), 10); //10min | |
} catch (ServerException $e) { | |
Cache::flush(); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment