自定义字段指令/解析器

问题描述

我需要能够让客户端在其查询中将一列指定为字符串,然后为该字段计算浮点值。指定列中的所有值都是浮点值,我想获取所有行的平均值。我在graphql-playground中尝试的查询可能看起来像这样:

query {
  someBehavior {
    likelihood @likelihood(column: "L11")
  }
}

我的查询类型如下:

type Query {
    # not sure if the directive needs to be on the Query type or the Behavior type o
    someBehavior(where: _ @whereConditions(columnsEnum: "BehaviorEnum")): Behavior! @likelihood
}

BehaviorEnum看起来像这样:

enum BehaviorEnum {
    likelihood @enum(value: "likelihood") # not sure what the value should be here
}

我的行为类型如下:

type Behavior {
    # error is being thrown when using directive here
    #likelihood: Float! @likelihood
    likelihood: Float!
}

我的指令定义如下:

directive @likelihood(
    column: String!
) on FIELD | FRAGMENT_SPREAD | INLINE_FRAGMENT

我目前对如何实现这个目标有些困惑。我相信我需要一个字段指令,该指令的类(LikelihoodDirective.PHP)和该查询的解析器(SomeBehavior.PHP)。我不确定大部分逻辑应该在哪里进行,并且正在努力执行任何日志记录。 我一直在看我可以找到的每个示例,并将其拼凑成指令类中的一个函数,但是$ column返回为null,因此某些操作无效。

  public function handleField(FieldValue $fieldValue,Closure $next): FieldValue
  {
    // Retrieve the existing resolver function
    $originalResolver = $fieldValue->getResolver();

    return $next(
      $fieldValue->setResolver(
        function ($root,array $args,GraphQLContext $context,ResolveInfo $resolveInfo) use ($originalResolver) {
          $column = $this->directiveArgValue('column');
          // Throw in case of an invalid schema deFinition to remind the developer
          if ($column === null) {
            throw new DeFinitionException("Missing argument 'column' for directive '@likelihood'.");
          }

          return $originalResolver($root,$args,$context,$resolveInfo);
        }
      )
    );
  }

我需要捕获列字符串并将该值放入雄辩的查询中(我认为是在解析器中)

$likelihood = MyData::avg(???);

任何人都可以为实现这一目标提供帮助吗?这可能吗?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)