Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow global resolver Middlewares #1127

Merged
merged 7 commits into from
Mar 4, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 7 additions & 2 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,8 +1,13 @@
CHANGELOG
=========

[Next release](https://github.com/rebing/graphql-laravel/compare/9.3.0...master)
--------------
[Next release](https://github.com/rebing/graphql-laravel/compare/9.4.0...master)

2024-02-27, 9.4.0
-----------------

## Added
- Possibility to add resolver middleware at runtime using `GraphQL::appendGlobalResolverMiddleware(YourMiddleware::class)` or `GraphQL::appendGlobalResolverMiddleware(new YourMiddleware(...))`

2024-02-18, 9.3.0
-----------------
Expand Down
22 changes: 22 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -1151,6 +1151,28 @@ Alternatively, you can override `getMiddleware` to supply your own logic:
}
```

If you want to register middleware globally, use the `resolver_middleware_append` key in `config/graphql.php`:

```php
return [
...
'resolver_middleware_append' => [YourMiddleware::class],
];
```

You can also use the `appendGlobalResolverMiddleware` method in any ServiceProvider:

```php
...
public function boot()
{
...
GraphQL::appendGlobalResolverMiddleware(YourMiddleware::class);
// Or with new instance
GraphQL::appendGlobalResolverMiddleware(new YourMiddleware(...));
}
```

#### Terminable middleware

Sometimes a middleware may need to do some work after the response has been sent to the browser.
Expand Down
5 changes: 5 additions & 0 deletions config/config.php
Original file line number Diff line number Diff line change
Expand Up @@ -214,4 +214,9 @@
Rebing\GraphQL\Support\ExecutionMiddleware\AddAuthUserContextValueMiddleware::class,
// \Rebing\GraphQL\Support\ExecutionMiddleware\UnusedVariablesMiddleware::class,
],

/*
* Globally registered ResolverMiddleware
*/
'resolver_middleware_append' => null,
];
27 changes: 26 additions & 1 deletion src/GraphQL.php
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,13 @@ class GraphQL
*/
protected $types = [];

/**
* These middleware are executed before all resolve methods
*
* @var array<object|class-string>
*/
protected $globalResolverMiddlewares = [];

/** @var Type[] */
protected $typesInstances = [];

Expand Down Expand Up @@ -186,6 +193,24 @@ protected function appendGraphqlExecutionMiddleware(array $middlewares): array
return $middlewares;
}

/**
* @phpstan-param class-string|object $class
*/
public function appendGlobalResolverMiddleware(object|string $class): void
{
$this->globalResolverMiddlewares[] = $class;
}

/**
* @phpstan-return array<object|class-string>
*/
public function getGlobalResolverMiddlewares(): array
{
$resolverMiddlewares = $this->config->get('graphql.resolver_middleware_append') ?? [];

return array_merge($resolverMiddlewares, $this->globalResolverMiddlewares);
}

/**
* @param array<int|string,string> $types
*/
Expand Down Expand Up @@ -501,8 +526,8 @@ public function wrapType(string $typeName, string $customTypeName, string $wrapp
}

/**
* @see \GraphQL\Executor\ExecutionResult::setErrorFormatter
* @return array<string,mixed>
* @see \GraphQL\Executor\ExecutionResult::setErrorFormatter
*/
public static function formatError(Error $e): array
{
Expand Down
2 changes: 2 additions & 0 deletions src/Support/Facades/GraphQL.php
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,8 @@
* @method static Schema buildSchemaFromConfig(array $schemaConfig)
* @method static array getSchemas()
* @method static void addSchema(string $name, Schema $schema)
* @method static array getGlobalResolverMiddlewares()
* @method static void appendGlobalResolverMiddleware(object|string $class)
* @method static void addType(object|string $class, string $name = null)
* @method static Type objectType(ObjectType|array|string $type, array $opts = [])
* @method static array formatError(Error $e)
Expand Down
14 changes: 12 additions & 2 deletions src/Support/Field.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
use Rebing\GraphQL\Error\AuthorizationError;
use Rebing\GraphQL\Error\ValidationError;
use Rebing\GraphQL\Support\AliasArguments\AliasArguments;
use Rebing\GraphQL\Support\Facades\GraphQL;
use ReflectionMethod;

/**
Expand Down Expand Up @@ -145,6 +146,15 @@ protected function getMiddleware(): array
return $this->middleware;
}

/**
* @return array<class-string|object>
* @phpstan-param array<string> $middleware
*/
protected function appendGlobalMiddlewares(array $middleware): array
{
return array_merge($middleware, GraphQL::getGlobalResolverMiddlewares());
}

protected function getResolver(): ?Closure
{
$resolver = $this->originalResolver();
Expand All @@ -154,7 +164,7 @@ protected function getResolver(): ?Closure
}

return function ($root, ...$arguments) use ($resolver) {
$middleware = $this->getMiddleware();
$middleware = $this->appendGlobalMiddlewares($this->getMiddleware());

return app()->make(Pipeline::class)
->send(array_merge([$this], $arguments))
Expand All @@ -165,7 +175,7 @@ protected function getResolver(): ?Closure

foreach ($middleware as $name) {
/** @var Middleware $instance */
$instance = app()->make($name);
$instance = \is_object($name) ? $name : app()->make($name);

if (method_exists($instance, 'terminate')) {
app()->terminating(function () use ($arguments, $instance, $result): void {
Expand Down
32 changes: 32 additions & 0 deletions tests/Support/Middlewares/GlobalInstanceMiddleware.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
<?php

declare(strict_types = 1);
namespace Rebing\GraphQL\Tests\Support\Middlewares;

use Closure;
use Exception;
use GraphQL\Type\Definition\ResolveInfo;
use Rebing\GraphQL\Support\Middleware;

class GlobalInstanceMiddleware extends Middleware
{
protected int $invalidValue;

public function __construct(int $invalidValue)
{
$this->invalidValue = $invalidValue;
}

/**
* @phpstan-param mixed $root
* @phpstan-param mixed $context
*/
public function handle($root, array $args, $context, ResolveInfo $info, Closure $next): mixed
{
if (isset($this->invalidValue) && $this->invalidValue === $args['index']) {
throw new Exception('Index is not allowed');
}

return $next($root, $args, $context, $info);
}
}
18 changes: 18 additions & 0 deletions tests/Support/Middlewares/GlobalMiddleware.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
<?php declare(strict_types = 1);
namespace Rebing\GraphQL\Tests\Support\Middlewares;

use Closure;
use GraphQL\Type\Definition\ResolveInfo;
use Rebing\GraphQL\Support\Middleware;

class GlobalMiddleware extends Middleware
{
/**
* @phpstan-param mixed $root
* @phpstan-param mixed $context
*/
public function handle($root, array $args, $context, ResolveInfo $info, Closure $next): mixed
{
return [['test' => 'Intercepted by GlobalMiddleware']];
}
}
36 changes: 36 additions & 0 deletions tests/Unit/GlobalMiddlewareTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
<?php

declare(strict_types = 1);
namespace Rebing\GraphQL\Tests\Unit;

use Rebing\GraphQL\Support\Facades\GraphQL;
use Rebing\GraphQL\Tests\Support\Middlewares\GlobalInstanceMiddleware;
use Rebing\GraphQL\Tests\Support\Middlewares\GlobalMiddleware;
use Rebing\GraphQL\Tests\TestCase;

class GlobalMiddlewareTest extends TestCase
{
public function testConfigGlobalMiddlewareExecuted(): void
{
$this->app['config']->set('graphql.resolver_middleware_append', [
GlobalMiddleware::class,
]);
$result = GraphQL::queryAndReturnResult($this->queries['examples']);
self::assertSame(['examples' => [['test' => 'Intercepted by GlobalMiddleware']]], $result->data);
}

public function testFacadeGlobalMiddlewareExecuted(): void
{
GraphQL::appendGlobalResolverMiddleware(GlobalMiddleware::class);
$result = GraphQL::queryAndReturnResult($this->queries['examples']);
self::assertSame(['examples' => [['test' => 'Intercepted by GlobalMiddleware']]], $result->data);
}

public function testCanUseMiddlewareInstance(): void
{
GraphQL::appendGlobalResolverMiddleware(new GlobalInstanceMiddleware(0));
$result = GraphQL::queryAndReturnResult($this->queries['examplesWithVariables'], ['index' => 0]);
self::assertObjectHasProperty('errors', $result);
self::assertSame('Index is not allowed', $result->errors[0]->getMessage());
}
}