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 3 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)`

2024-02-18, 9.3.0
-----------------
Expand Down
10 changes: 10 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -1150,6 +1150,16 @@ Alternatively, you can override `getMiddleware` to supply your own logic:
return array_merge([...], $this->middleware);
}
```
If you want to register middleware globally, use can use the `appendGlobalResolverMiddleware` method in ServiceProvider:

```php
...
public function boot()
{
...
GraphQL::appendGlobalResolverMiddleware(YourMiddleware::class);
}
```

#### Terminable middleware

Expand Down
23 changes: 23 additions & 0 deletions 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,22 @@ 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
{
return $this->globalResolverMiddlewares;
}

/**
* @param array<int|string,string> $types
*/
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
19 changes: 19 additions & 0 deletions tests/Support/Middlewares/GlobalMiddleware.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
<?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
* @phpstan-return mixed
*/
public function handle($root, array $args, $context, ResolveInfo $info, Closure $next): mixed
{
return parent::handle($root, $args, $context, $info, $next);
}
}
14 changes: 14 additions & 0 deletions tests/Unit/MiddlewareTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
namespace Rebing\GraphQL\Tests\Unit;

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

class MiddlewareTest extends TestCase
Expand Down Expand Up @@ -79,4 +80,17 @@ public function testMiddlewareTerminateHappensAfterResponseIsSent(): void
self::assertObjectHasProperty('errors', $result);
self::assertMatchesRegularExpression('/^Undefined .* 6$/', $result->errors[0]->getMessage());
}

public function testGlobalMiddlewareExecuted(): void
{
$mock = $this->partialMock(GlobalMiddleware::class);
GraphQL::appendGlobalResolverMiddleware($mock);
$result = GraphQL::queryAndReturnResult($this->queries['exampleMiddleware'], [
'index' => 2,
]);
$mock->shouldHaveReceived('handle');

self::assertObjectHasProperty('errors', $result);
self::assertSame('Example 3 is not allowed', $result->errors[0]->getMessage());
}
}