我有以下查询设置:
extend type Query {
positionGroups(quoteId: ID): [PositionGroup!]! @all
}
type PositionGroup {
...
positions: [Position!]!
}
type Position {
...
amount: Amount @amountEnhancedWithQuoteAmountInfo
}Position中的amount通常会返回默认值,但如果我们处于特定quote的上下文中,它可能会发生变化。这就是AmountEnhancedWithQuoteAmountInfoDerictive应该做的。
因此在AmountEnhancedWithQuoteAmountInfoDerictive中,我需要quoteId值(如果有的话)。然后,我可以应用一些额外的逻辑从数据库中获取特定于报价的金额。如果没有给出quoteId,我就不需要做任何额外的事情。
我的指令看起来像这样:
class AmountEnhancedWithLBHQuoteAmountInfoDirective extends BaseDirective implements FieldResolver
{
/**
* @inheritDoc
*/
public function resolveField(FieldValue $fieldValue)
{
$this->$fieldValue->setResolver(function ($root, $args, GraphQLContext $context, ResolveInfo $resolveInfo) {
$value = $root->amount;
$something->quoteId; // What should this be?
// Change $value based on the quote
return $value;
});
return $fieldValue;
}
}$root变量只是我的Position,我在其他参数中也找不到quoteId。
那么有没有办法访问那里的quoteId呢?
我能想到的一种方法是为每个部分编写自定义查询,然后简单地传递quoteId。不过,有没有更好的方法呢?
注意:Position与Quote没有任何关系,但是,在报价的上下文中,我想在其基础上添加一些额外的信息。因此,如果用户不给出一个Quote参数,就无法知道查询是关于什么quoteId的。
发布于 2020-12-18 00:56:52
我自己构建了一个解决方案,我创建了一个PassAlongDirective,它会将参数或字段传递给孩子:
class PassAlongDirective extends BaseDirective implements FieldMiddleware, DefinedDirective
{
public static function definition(): string
{
return 'Passes along parameters to children.';
}
public function handleField(FieldValue $fieldValue, Closure $next): FieldValue
{
$resolver = $fieldValue->getResolver();
$fieldsToPassAlong = $this->directiveArgValue('fields', []);
$fieldValue->setResolver(function ($root, array $args, GraphQLContext $context, ResolveInfo $resolveInfo) use ($resolver, $fieldsToPassAlong) {
$result = $resolver($root, $args, $context, $resolveInfo);
foreach ($fieldsToPassAlong as $field) {
$value = $args[$field] ?? $root->{$field} ?? null;
if ($value) {
$this->passAlongTo($result, $field, $value);
}
}
return $result;
});
return $next($fieldValue);
}
private function passAlongTo($result, $field, $value)
{
if ($result instanceof Collection || $result instanceof Paginator) {
foreach ($result as $item) {
$this->setField($item, $field, $value);
}
} else {
$this->setField($result, $field, $value);
}
}
private function setField($item, $field, $value)
{
$item->{$field} = $value;
}
}它的用法如下:
positionGroups(quoteId: ID): [PositionGroup!]! @all @passAlong(fields: ["quoteId"])https://stackoverflow.com/questions/65343669
复制相似问题