【发布时间】:2020-12-14 04:57:27
【问题描述】:
你好吗?
我正在与工会作斗争。我想澄清一下基于自定义类型的工会类型的自定义解析器。我当前的架构是 product.graphql 的 schema.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)为什么灯塔无法加载类型。
你能告诉我正确的处理方法吗?
请记住
- ProductDish 和 ProductDrink 是 不是 Eloquent 模型,而是产品类型上产品 json 字段属性的简单“包装器”,这是一个 eloquent 模型
- ProductServing 也是如此,这是一个键:值对
- 如果我删除联合,一切正常。我的意思是,如果 Product 类型具有分配给 ProductDish 类型或 ProductDrink 的属性,则一切正常,但我需要联合
【问题讨论】:
标签: php laravel graphql laravel-lighthouse