Reputation: 51
My question is regarding the custom directives https://lighthouse-php.com/4.11/the-basics/directives.html#definition
My schema is:
type Query {
sayFriendly: String @append(text: ", please.")
}
in lighthouse.php the config, I already have
'namespaces' => [
'models' => ['App', 'App\\Models'],
'queries' => 'App\\GraphQL\\Queries',
'mutations' => 'App\\GraphQL\\Mutations',
'subscriptions' => 'App\\GraphQL\\Subscriptions',
'interfaces' => 'App\\GraphQL\\Interfaces',
'unions' => 'App\\GraphQL\\Unions',
'scalars' => 'App\\GraphQL\\Scalars',
'directives' => ['App\\GraphQL\\Directives'],
],
directive enabled.
I defined the directive at \App\GraphQL\Directives\appendDirective as
<?php
namespace App\GraphQL\Directives;
use Closure;
use GraphQL\Type\Definition\ResolveInfo;
use Nuwave\Lighthouse\Schema\Values\FieldValue;
use Nuwave\Lighthouse\Support\Contracts\Directive;
use Nuwave\Lighthouse\Support\Contracts\FieldMiddleware;
use Nuwave\Lighthouse\Support\Contracts\GraphQLContext;
class appendDirective implements Directive, FieldMiddleware
{
/**
* Name of the directive as used in the schema.
*
* @return string
*/
public function name(): string
{
return 'append';
}
/**
* Wrap around the final field resolver.
*
* @param \Nuwave\Lighthouse\Schema\Values\FieldValue $fieldValue
* @param \Closure $next
* @return \Nuwave\Lighthouse\Schema\Values\FieldValue
*/
public function handleField(FieldValue $fieldValue, Closure $next): FieldValue
{
// Retrieve the existing resolver function
/** @var Closure $previousResolver */
$previousResolver = $fieldValue->getResolver();
// Wrap around the resolver
$wrappedResolver = function ($root, array $args, GraphQLContext $context, ResolveInfo $info) use ($previousResolver): string {
// Call the resolver, passing along the resolver arguments
/** @var string $result */
$result = $previousResolver($root, $args, $context, $info);
return ($result);
};
// Place the wrapped resolver back upon the FieldValue
// It is not resolved right now - we just prepare it
$fieldValue->setResolver($wrappedResolver);
// Keep the middleware chain going
return $next($fieldValue);
}
}
how can I get the value of key "text" from my directive and append to $result [ @append(text: ", please.") ]. The $args is an empty array (and It should be because I did make parameterized query [sayFriendly] )
Upvotes: 4
Views: 4238
Reputation: 1638
If you extend your directive from Nuwave\Lighthouse\Schema\Directives\BaseDirective
you can have access to $this->directiveArgValue('text');
to retrieve the text argument to your custom directive.
The $args
are empty because that are the arguments supplied by the client in the query, in the sayFriendly
query example there are no args possible so that will always be empty.
As a tip: you can find this out by looking at an already implemented directives inside Lighthouse, the documentation is a bit thin on the custom directives but you can learn a lot by looking at the directives provided by Lighthouse.
Upvotes: 4