【问题标题】:How to get index from array - graphql?如何从数组中获取索引 - graphql?
【发布时间】:2019-07-30 18:35:54
【问题描述】:

当下游响应没有返回数组项索引时,我需要知道它。假设我的架构看起来像

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 数组中获取ith index

【问题讨论】:

  • 如果是顺序记录上一个索引,那么你就知道下一个是什么了..
  • 我编辑了解析器并发表了评论 - 它在 info 对象中吗?
  • 可以将其称为 id 而不是 index 并自动递增它,然后以与获取名称相同的方式获取它..
  • 我们可以在购物车的解析器中放入一些东西,然后通过项目对象从那里传递 id/index 吗?它是数组并自动解析为 Item 类型。

标签: javascript arrays node.js express graphql


【解决方案1】:

如果你想为 item 中的一张卡 reutrn 多个 item 那么

  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
  }
}

解析器 reutrn 索引或基于 itemId 的结果。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-10-25
    • 1970-01-01
    • 1970-01-01
    • 2019-01-06
    • 2022-01-12
    • 2018-09-01
    • 2020-06-19
    • 1970-01-01
    相关资源
    最近更新 更多