我正在使用我的 GraphQL 实例的接口,但这个问题可能也适用于联合。所有实现接口的类型都有 2 个公共字段,但是每种类型都有多个附加字段。
给定以下架构
interface FoodType {
id: String
type: String
}
type Pizza implements FoodType {
id: String
type: String
pizzaType: String
toppings: [String]
size: String
}
type Salad implements FoodType {
id: String
type: String
vegetarian: Boolean
dressing: Boolean
}
type BasicFood implements FoodType {
id: String
type: String
}
和以下解析器
{
Query: {
GetAllFood(root) {
return fetchFromAllFoodsEndpoint()
.then((items) => {
return mergeExtraFieldsByType(items);
});
},
},
FoodType: {
__resolveType(food) {
switch (food.type) {
case 'pizza': return 'Pizza';
case 'salad': return 'Salad';
default: return 'BasicFood';
}
},
},
Pizza: {
toppings({pizzaType}) {
return fetchFromPizzaEndpoint(pizzaType);
}
}
}
如何获取每种类型的附加字段?
目前,我可以allFood
获取所有食物以获取 和 的基本id
字段type
。在此之后,我将遍历结果,如果找到任何 type Pizza
,我将调用 to fetchFromPizzaEndpoint
,获取附加字段并将它们合并到原始基本类型中。我对每种类型都重复这个。
我还能够手动解析特定字段,一个类型,例如Pizza.toppings
,如上所示。
现在我的解决方案并不理想,我更希望能够为每种类型解析多个字段,就像我对单个字段所做的那样toppings
。GraphQL 可以做到这一点吗?必须有更好的方法来实现这一点,因为这是一个非常常见的用例。
理想情况下,我希望能够在我的解析器中知道我的查询要求哪些片段,因此我只能调用被要求的端点(每个片段一个端点)。
{
Query: {
GetAllFood(root) {
return fetchFromAllFoodsEndpoint();
},
},
FoodType: {
__resolveType(food) {
switch (food.type) {
case 'pizza': return 'Pizza';
case 'salad': return 'Salad';
default: return 'BasicFood';
}
},
},
Pizza: {
__resolveMissingFields(food) {
return fetchFromPizzaEndpoint(food.id);
}
},
Salad: {
__resolveMissingFields(food) {
return fetchFromSaladEndpoint(food.id);
}
}
}