灯塔找不到我的自定义联盟类型

问题描述

你好吗?

我在工会方面苦苦挣扎,我想对基于自定义类型的联合类型的自定义解析程序进行一些说明。我当前的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无法理解自定义类型。我为类型创建了两个类:

// 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",];
        parent::__construct($config);
    }
}

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

// 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)为什么灯塔无法加载类型。

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

请记住

  • Productdish ProductDrink 不是口才的模型,而是产品类型上产品json字段属性的简单“包装”,这是一个口才好的模型
  • 产品服务相同,这是一个键:值对
  • 如果我移除工会,一切都会正常。我的意思是,如果产品类型具有分配给Productdish类型或ProductDrink的属性,那么一切都可以顺利进行,但我需要联合

解决方法

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

首先,在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联合类