我的问题是关于自定义指令 https://lighthouse-php.com/4.11/the-basics/directives.html#definition
我的模式是:
type Query {
sayFriendly: String @append(text: ", please.")
}
在lighthouse.php的配置中,我已经拥有
'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'],
],
启用了指令。
我在\ App \ GraphQL \ Directives \ appendDirective中将指令定义为
<?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);
}
}
如何从指令中获取键“ text”的值并将其追加到$ result [@append(text:“,please。”)]。 $ args是一个空数组(这应该是因为我确实进行了参数化查询[sayFriendly])
答案 0 :(得分:2)
如果您从Nuwave\Lighthouse\Schema\Directives\BaseDirective
扩展指令,则可以访问$this->directiveArgValue('text');
来检索自定义指令的text参数。
$args
为空,因为这是客户端在查询中提供的参数,在sayFriendly
查询示例中,没有可能的参数,因此始终为空。
提示:您可以通过查看Lighthouse内部的already implemented directives来了解这一点,文档中的自定义指令有些精简,但是您可以通过查看灯塔。