首页 > 解决方案 > 多边形灯塔graphql类型

问题描述

我在我的 laravel 5.7 应用程序中使用灯塔 PHP。我试图在我的模式中定义一个几何场(多边形),但效果不佳。

谁能帮助我如何在我的 graphql 模式中定义多边形字段。 架构和查询代码

标签: phplaravelgraphqlpolygonlaravel-lighthouse

解决方案


根据您的图像,您尚未为Polygon.

由于您还没有真正指定要如何说明多边形,因此我将展示一个示例。在这个例子中,我将创建一个新的 GraphQl Scalar 类型。

指定多边形的常用方法是使用一组坐标集,如下所示

((35 10, 45 45, 15 40, 10 20, 35 10),(20 30, 35 35, 30 20, 20 30))

为了表示这一点,我将创建一个新的标量

"A string representation of a polygon e.g. `((35 10, 45 45, 15 40, 10 20, 35 10),(20 30, 35 35, 30 20, 20 30))`."
scalar Polygon @scalar(class: "Your\\Classname\\Polygon")

然后创建必须解析/验证字符串的类

use GraphQL\Error\Error;
use GraphQL\Language\AST\Node;
use GraphQL\Language\AST\StringValueNode;
use GraphQL\Type\Definition\ScalarType;

class Polygon extends ScalarType
{

    /**
     * Serializes an internal value to include in a response.
     *
     * @param mixed $value
     *
     * @return mixed
     *
     * @throws Error
     */
    public function serialize($value)
    {
        if ($value instanceof Geometry\Polygon) {
            $value->toString();
        }

        return (new Geometry\Polygon($value))->toString();
    }

    /**
     * Parses an externally provided value (query variable) to use as an input
     *
     * In the case of an invalid value this method must throw an Exception
     *
     * @param mixed $value
     *
     * @return mixed
     *
     * @throws Error
     */
    public function parseValue($value)
    {
        return new Geometry\Polygon($value);
    }

    /**
     * Parses an externally provided literal value (hardcoded in GraphQL query) to use as an input
     *
     * In the case of an invalid node or value this method must throw an Exception
     *
     * @param Node         $valueNode
     * @param mixed[]|null $variables
     *
     * @return mixed
     *
     * @throws Exception
     */
    public function parseLiteral($valueNode, ?array $variables = null)
    {
        if (! $valueNode instanceof StringValueNode) {
            throw new Error(
                "Query error: Can only parse strings, got {$valueNode->kind}",
                [$valueNode]
            );
        }

        return new Geometry\Polygon($valueNode->value);
    }
}

我还没有实现Geometry\Polygon类的逻辑,并且对这种类型的输入和标量类型的所有验证也可能需要一些调整。但这基本上是在 Ligthouse 中创建 Polygon Scalar 类型的方式。

有了这个,您就可以在您的areazone字段中输入一个具有上面指定格式的字符串,并在您的代码中将它作为一个Geometry\Polygon类来获取。

您可以在Lighthouse 文档中阅读有关标量的更多信息。


推荐阅读