Lighthouse 找不到我的自定义 Union 类型

Lighthouse can't find my custom Types for Union

你好吗?

我正在为联合而苦苦挣扎 我想要一些关于基于自定义类型的联合类型的自定义解析器的说明。我当前的架构是 product.graphql 的,它是在 schema.graphql

中导入的
type ProductServing {
    name: String
    price: Float
}

type ProductDish {
    price: Float
    calories: Int
    servings: [ProductServing]
}

type ProductDrink {
    price: Float
    servings: [ProductServing]
}

union ProductProperties = ProductDish | ProductDrink

type Product {
    id: ID!
    user: User! @belongsTo
    media: Media
    blocks: [Block]! @belongsToMany
    slug: String!
    name: String!
    description: String
    properties: ProductProperties!
    activated_at: DateTime
    created_at: DateTime!
    updated_at: DateTime!
} 

当然,仅此模式是行不通的,因为 Lighthouse 无法理解自定义类型。我为类型创建了两个 classes:

// App\GraphQL\Types
class ProductDish extends ObjectType
{
    public function __construct()
    {
        $config = [
            "name" => "ProductDish",
            "fields" => [
                "__type" => Type:string(),
                "price" => Type::float(),
                "calories" => Type::int(),
            ],
        ];
        parent::__construct($config);
    }
}

class ProductDrink extends ObjectType
{
    public function __construct()
    {
        $config = [
            "name" => "ProductDrink",
            "fields" => [
                "__type" => Type:string(),
                "price" => Type::float(),
            ],
        ];
        parent::__construct($config);
    }
}

以及使用 __invoke 方法的 ProductProperties 的联合 class

// App\GraphQL\Unions;
public function __invoke($rootValue, GraphQLContext $context, ResolveInfo $resolveInfo) : Type
{
    $type = $rootValue["__type"];
    switch ($type) {
        case "dish" :
            return $this->typeRegistry->get(ProductDish::class);
        case "drink":
            return $this->typeRegistry->get(ProductDrink::class);
    }
    return $this->typeRegistry->get(class_basename($rootValue));
}

这行不通,否则我不会在这里,看着 graphql-playground 我收到这条消息

"debugMessage": "Lighthouse failed while trying to load a type: App\GraphQL\Types\ProductDish\n\nMake sure the type is present in your schema definition.\n"

问题是我不确定 1) 这是否是正确的方法 2) 为什么灯塔无法加载类型。

你能告诉我正确的处理方法吗?

请记住

我走在正确的轨道上,但我需要解决一些问题

首先,在 ProductProperties 文件中,注册表需要一个简单的字符串而不是命名空间,所以我不得不输入 ->get("ProductDish") 而不是 ->get(ProductDish::class) 然后我删除了 __type 字段在我的类型和 graphql 模式中,因为我可以在 Product 模型中使用一个 mutator,并根据一些参数确定哪种类型,像这样

public function getPropertisAttribute($properties) {
    
   $properties = json_decode($properties, true);

   $properties["__type"] = // .. some logic to get the right type

   return $properties;
}

一旦我有了一个类型,我就可以将它用回我的 ProductProperties 联合 class