x-graphql/field-middleware

Adding custom logics before and after when resolving fields

0.2.0 2024-03-29 09:41 UTC

This package is auto-updated.

Last update: 2024-11-29 11:07:55 UTC


README

Adding custom logics before and after when resolving fields

unit tests codecov

Getting Started

Install this package via Composer

composer require x-graphql/field-middleware

Usages

Create your first middleware:

use GraphQL\Type\Definition\ResolveInfo;
use GraphQL\Type\Schema;
use XGraphQL\FieldMiddleware\MiddlewareInterface;

class MyMiddleware implements MiddlewareInterface {

    public function resolve(mixed $value, array $arguments, mixed $context, ResolveInfo $info, callable $next) : mixed {
        $firstName = $next($value, $arguments, $context, $info);
        
        return $firstName . ' Doe';
    }
}

Then let apply this middleware to schema:

use GraphQL\GraphQL;
use GraphQL\Type\Definition\ObjectType;
use GraphQL\Type\Definition\Type;
use GraphQL\Type\Schema;
use XGraphQL\FieldMiddleware\FieldMiddleware;

$schema = new Schema([
  'query' => new ObjectType([
    'name' => 'Query',
    'fields' => [
      'name' => Type::string()
    ],
  ]),
]);

FieldMiddleware::apply($schema, [new MyMiddleware()]);

$result = GraphQL::executeQuery($schema, '{ name }', ['name' => 'John']);

var_dump($result->toArray());

Credits

Created by Minh Vuong