Skip to content

Adding custom logics before and after when resolving fields

License

Notifications You must be signed in to change notification settings

x-graphql/field-middleware

Repository files navigation

Field Middleware

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

About

Adding custom logics before and after when resolving fields

Resources

License

Code of conduct

Stars

Watchers

Forks

Packages

No packages published

Languages