当下游响应未返回数组项索引时,我需要知道数组项索引。假设我的架构看起来像
schema:
type Cart {
items: [Item]
}
type Item {
name: String
index: Int
}
数据来了:
{items: [{name: apple}, {name: mango},]}
解析器看起来像:
Cart: {
items(obj, context, info) {
return obj;
}
}
Item: {
name(obj, context, info) {
return obj.name;
}
index(obj, context, info) {
// how to get it?
}
}
如何获取items数组中的第i个索引
?
最佳答案
如果您想为项目中的一张卡重新显示多个项目,则
type Cart {
items: [Item]!
}
type Item {
name: String!
index: Int!
}
Query {
cardItems: [Cart]!
}
resolver {
cardItems : () => {
//Perform opration and make result like this to run query properly
return [{ items: [{ name: 'name1', index: 0 }, ...]}]
//Which is array of items contain name and index
}
}
// Query to get result
{
cardItems {
items {
name
index
}
}
}
但是,如果您想要购物车中商品的特定索引,您应该获取 id 或索引唯一键并进行另一个查询
Query {
itemById(itemId: String!): Item
}
resolver {
itemById({ itemId }) {
//perform opration and return item with respeact to itemId
return { name: 'string', index: 1}
},
}
//Query to get result
{
itemById(itemId: "1"){
name
index
}
}
解析器返回基于索引或 itemId 的结果。
关于javascript - 如何从数组中获取索引 - graphql?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55068107/