gpt4 book ai didi

node.js - 如何使用 GraphQL 和 ApolloStack 解析联合/接口(interface)字段

转载 作者:搜寻专家 更新时间:2023-10-31 22:22:43 26 4
gpt4 key购买 nike

我正在使用我的 GraphQL 实例的接口(interface),但这个问题可能也适用于联合。实现该接口(interface)的所有类型都有 2 个公共(public)字段,但是每种类型都有多个附加字段。

给定以下架构

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 获取所有食物以获得idtype 的基本字段。在此之后,我将遍历结果,如果找到类型为 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);
}
}
}

最佳答案

我知道这个问题已有 5 个月大,但我希望这能帮助其他人解决这个问题。他正在传递结构如下的解析器

{
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);
}
}
}

但他真的想要类似的东西(不完全是,但我强调的是 __resolveType 相对于 Query 的位置)

{
Query: {
GetAllFood(root) {
return fetchFromAllFoodsEndpoint()
.then((items) => {
return mergeExtraFieldsByType(items);
});
},
},
FoodType: {
__resolveType(data, ctx, info) {
return whatIsTheType(data, ctx, info)
}
}
}

官方文档有例子here ,但它只包括接口(interface)类型,我觉得这很困惑。我还有一个联合类型的额外完整可运行示例(配置与接口(interface)相同)here

关于node.js - 如何使用 GraphQL 和 ApolloStack 解析联合/接口(interface)字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41630743/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com