0

我为自定义电子邮件类型复制了 Lighthouse 网站链接到 ( https://webonyx.github.io/graphql-php/type-system/scalar-types/ ) 的示例。(见下面的代码)

不幸的是,如果我现在转到 graphql-playground,我会收到 500 错误,说明:“没有为标量电子邮件找到 GraphQL\Type\Definition\ScalarType 的匹配子类”

我该如何解决这个错误?

<?php
// file: /graphql/EmailType.php

namespace MyApp;

use GraphQL\Error\Error;
use GraphQL\Error\InvariantViolation;
use GraphQL\Language\AST\StringValueNode;
use GraphQL\Type\Definition\ScalarType;
use GraphQL\Utils\Utils;

class EmailType extends ScalarType
{
    // Note: name can be omitted. In this case it will be inferred from class name 
    // (suffix "Type" will be dropped)
    public $name = 'Email';

    /**
     * Serializes an internal value to include in a response.
     *
     * @param string $value
     * @return string
     */
    public function serialize($value)
    {
        // Assuming internal representation of email is always correct:
        return $value;
    }

    /**
     * Parses an externally provided value (query variable) to use as an input
     *
     * @param mixed $value
     * @return mixed
     */
    public function parseValue($value)
    {
        if (!filter_var($value, FILTER_VALIDATE_EMAIL)) {
            throw new Error("Cannot represent following value as email: " . Utils::printSafeJson($value));
        }
        return $value;
    }

    /**
     * Parses an externally provided literal value (hardcoded in GraphQL query) to use as an input.
     * 
     * E.g. 
     * {
     *   user(email: "user@example.com") 
     * }
     *
     * @param \GraphQL\Language\AST\Node $valueNode
     * @param array|null $variables
     * @return string
     * @throws Error
     */
    public function parseLiteral($valueNode, array $variables = null)
    {
        // Note: throwing GraphQL\Error\Error vs \UnexpectedValueException to benefit from GraphQL
        // error location in query:
        if (!$valueNode instanceof StringValueNode) {
            throw new Error('Query error: Can only parse strings got: ' . $valueNode->kind, [$valueNode]);
        }
        if (!filter_var($valueNode->value, FILTER_VALIDATE_EMAIL)) {
            throw new Error("Not a valid email", [$valueNode]);
        }
        return $valueNode->value;
    }
}
4

1 回答 1

0

(编辑:查看下面 Enzo Notario 的评论以获得真正的解决方案)

我通过以下方式解决了这个问题:

在“composer.json”中,我将文件夹“graphql”(EmailType 类文件所在的文件夹)添加到“autoload”中的文件夹列表中:

"autoload": {
        "psr-4": {
            "App\\": "app/"
        },
        "classmap": [
            "database/seeds",
            "database/factories",
            "graphql"
        ]
    },

然后我使用了以下命令(我很确定不需要最后一行):

php artisan clear-compiled
composer dumpautoload
composer update

在此之后,人按预期工作。

于 2019-12-24T18:48:58.937 回答