Adding custom logics before and after when resolving fields
Install this package via Composer
composer require x-graphql/field-middleware
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());
Created by Minh Vuong