我正在使用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的基本字段。在此之后,我循环遍历结果,如果发现任何Pizza类型的结果,我就调用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);
}
}
}https://stackoverflow.com/questions/41630743
复制相似问题