Skip to content

Instantly share code, notes, and snippets.

@urukalo
Created October 10, 2017 14:12
Show Gist options
  • Save urukalo/cb5215fe7aff1d2eed1b3e8f6957dafb to your computer and use it in GitHub Desktop.
Save urukalo/cb5215fe7aff1d2eed1b3e8f6957dafb to your computer and use it in GitHub Desktop.
<?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