laravel PHP Lighthouse用于舍入字段的简单自定义目录

mutmk8jj  于 2023-05-08  发布在  PHP
关注(0)|答案(1)|浏览(122)

我想创建一个简单的GrapQL指令@round,用于将浮点数舍入到设定的精度。
我设法让它工作,但解决方案困扰着我,我觉得我做错了一些事情。
这是我的简单类型,在sum字段中我使用@round指令。

type StatsPriceOutput {
    count: Int!
    sum: Float! @round(precision: 4)
}

RoundDirective的类:

final class RoundDirective extends BaseDirective implements FieldResolver
{
    public static function definition(): string {
        return /** @lang GraphQL */ <<<'GRAPHQL'
directive @round(precision: Int = 2) on FIELD_DEFINITION
GRAPHQL;
    }

    public function resolveField(FieldValue $fieldValue): FieldValue {
        $fieldValue->setResolver(function ($value) use ($fieldValue) { // $value returns both fields: count and sum. Expecting only sum
            $fieldName = $fieldValue->getFieldName();
            $precision = $this->directiveArgValue('precision', 2);
            return round($value[$fieldName], $precision);
        });
        return $fieldValue;
    }
}

我觉得我做错了什么,因为我清楚地在sum字段上设置了@round指令,但在$fieldValue->setResolver中,$value返回两个字段['count' => 'some value', 'sum' => 'some other value']的数组。
$value变量的转储:

我做错什么了吗?

tp5buhyn

tp5buhyn1#

setResolver接受具有以下签名解析器闭包:

function ($rootValue, array $args, GraphQLContext $context, ResolveInfo $resolveInfo)

要实现您想要的,使用FieldMiddleware更简单。
下面的实现假设你在Lighthouse 6.x上,使用Lighthouse 5的语法有点不同,请查看文档以获得适当的版本:https://lighthouse-php.com/master/custom-directives/getting-started.html#directive-interfaces

<?php

namespace App\GraphQL\Directives;

use Nuwave\Lighthouse\Execution\ResolveInfo;
use Nuwave\Lighthouse\Schema\Directives\BaseDirective;
use Nuwave\Lighthouse\Schema\Values\FieldValue;
use Nuwave\Lighthouse\Support\Contracts\FieldMiddleware;
use Nuwave\Lighthouse\Support\Contracts\GraphQLContext;

final class RoundDirective extends BaseDirective implements FieldMiddleware
{
    public static function definition(): string {
        return 'directive @round(precision: Int = 2) on FIELD_DEFINITION';
    }

    /**
     * Wrap around the final field resolver.
     */
    public function handleField(FieldValue $fieldValue): void
    {
        $fieldValue->wrapResolver(fn (callable $resolver) => 
            function (mixed $root, array $args, GraphQLContext $context, ResolveInfo $info) use ($resolver): string {
                $result = $resolver($root, $args, $context, $info);
                return round($result, $args['precision']);
            }
        );
    }
}

相关问题