繁体   English   中英

如何在GraphQL解析器中使用多个API调用来构造承诺数组,以返回单个对象类型列表

[英]How to architect array of promises in GraphQL resolver with multiple API calls to return a single object type list

我被困在我的GraphQL解析器中,它为公司的特定用户获取待办事项列表。 根据他们是否有权访问所有待办事项列表或少数几个待办事项列表,它将为已注册的用户拥有属于待办事项列表的组取回信息,并应将其取回。

到目前为止的代码能够记录查询中所请求的待办事项列表,但是我还没有找到有关如何实际返回用户注册组的所有待办事项列表数据的解决方案。

我选择将实际逻辑导出到单独的函数中

解析器:

allowedListItems: {
  type: new GraphQLList(TodoItem),
  resolve(parentValue, args) {
    return Promise.all([fetchAllowedItems(parentValue._id)]);
  }
},

承诺功能

function fetchAllowedItems(userId) {
  return User.findOne({ _id: userId }).then((user) => {
    if (user.todoGroups) {
      return user.todoGroups.map((groupId) => {
        return TodoGroup.findOne({ _id: groupId }).then(group => {
          return group.todoLists.map((listId) => {
            return TodoList.findOne({ _id: listId })
          })
        })
      })
    } else {
      return TodoList.find({ company: parentValue.company }).exec();
    }
  })
}

我没有从GraphQL收到任何错误,所以我想这是我让答辩者返回解析器的方式,如果您能帮助我,我将不胜感激!

更新:

我应该用Promise.all包装地图,因为映射返回一个数组。 尽管更新后的代码对返回的数据没有任何改善。

async resolve(parentValue, args) {
    let user = await User.findOne({ _id: parentValue._id })

    if (user.todoGroups) {
      return Promise.all(user.todoGroups.map((groupId) => {
        return TodoGroup.findOne({ _id: groupId }).then(group => {
          return Promise.all(group.todoLists.map((listId) => {
            return TodoList.findOne({ _id: listId });
          }))
        })
      }))
    } else {
      return TodoList.find({ company: parentValue.company }).exec();
    }
  }
},

当前查询结果:

{
  "data": {
    "user": {
      "_id": "5ba11690ad7a93d2b34d21a9",
      "allowedTodos": [
        {
          "_id": null,
          "title": null
        }
      ]
    }
  }
}

您需要在一个Promise.all数组上调用Promise.all ,而不是Promise.all 另外,您还必须在每个级别上调用它​​:

allowedListItems: {
  type: new GraphQLList(TodoItem),
  resolve(parentValue, args) {
    return User.findOne({ _id: parentValue._id }).then(user => {
      if (user.todoGroups) {
        return Promise.all(user.todoGroups.map(groupId => {
//             ^^^^^^^^^^^^
          return TodoGroup.findOne({ _id: groupId }).then(group => {
            return Promise.all(group.todoLists.map(listId => {
//                 ^^^^^^^^^^^^
              return TodoList.findOne({ _id: listId })
            }));
          });
        }));
      } else {
        return TodoList.find({ company: parentValue.company }).exec();
      }
    });
  }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM