【问题标题】:polygon lighthouse graphql type多边形灯塔graphql类型
【发布时间】:2019-07-26 16:49:33
【问题描述】:

我在我的 laravel 5.7 应用程序中使用 lighthouse PHP。我正在尝试在我的架构中定义一个几何场(多边形),但效果不佳。

谁能帮助我如何在我的 graphql 架构中定义多边形字段。 schema and query code

【问题讨论】:

  • 您能否将目前的代码添加到您的问题中?
  • 是的,完成@digijay
  • 多边形的类型定义在哪里?你得到什么错误?我想你应该看看Scalars

标签: php laravel graphql polygon laravel-lighthouse


【解决方案1】:

根据您的图像,您尚未为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 docs 中阅读有关标量的更多信息。

【讨论】:

    猜你喜欢
    • 2021-09-10
    • 1970-01-01
    • 2019-02-12
    • 2021-11-08
    • 2021-10-29
    • 1970-01-01
    • 1970-01-01
    • 2017-04-05
    • 2021-06-04
    相关资源
    最近更新 更多