你好吗?
我在工会方面苦苦挣扎,我想对基于自定义类型的联合类型的自定义解析程序进行一些说明。我当前的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",
"fields" => [
"__type" => Type:string(),
"price" => Type::float(),
],
];
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)为什么灯塔无法加载类型。
您能告诉我正确的处理方法吗?
请记住
答案 0 :(得分:0)
我在正确的轨道上,但我需要解决一些问题
首先,在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
联合类