Skip to content

Instantly share code, notes, and snippets.

@joshstar
Last active October 7, 2020 02:47
Show Gist options
  • Save joshstar/3c3ae3e61647e97977dcac5187da1deb to your computer and use it in GitHub Desktop.
Save joshstar/3c3ae3e61647e97977dcac5187da1deb to your computer and use it in GitHub Desktop.
Laravel GraphQL Middleware
<?php
namespace App\AniList\v2\GraphQL;
use Illuminate\Http\JsonResponse;
trait HasMiddleware
{
/**
* [handleMiddleware description]
* @param [type] $middlewares [description]
* @return [type] [description]
*/
public function handleMiddleware($middlewares = null)
{
if (env('SKIP_GRAPHQL_MIDDLEWARE', false)) {
return;
}
$appMiddleware = app()->router->getMiddleware();
if ($middlewares === null) {
$middlewares = $this->middleware;
}
foreach ($middlewares as $middleware) {
if (isset($appMiddleware[$middleware])) {
$next = app($appMiddleware[$middleware])->handle(request(), function(){});
if ($next instanceof JsonResponse) {
abort($next->getData()->status . '', $next->getData()->error . ' - ' . $next->getData()->error_message);
}
}
}
}
}
<?php
use Folklore\GraphQL\Support\Query;
use App\AniList\v2\GraphQL\HasMiddleware;
class MediaQuery extends Query {
use HasMiddleware;
protected $middleware = [
'auth'
];
public function resolve($root, $args, $context, ResolveInfo $info)
{
$this->handleMiddleware();
//...
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment