一个请求中的 GraphQL 多个查询 [英] GraphQL multiple queries in one request

查看:59
本文介绍了一个请求中的 GraphQL 多个查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的数据库中有一些用户创建的组.每个组中有多个成员.这是一个典型的群体:

I have some groups created by users in my database. Each group has multiple members in it. This is what a typical group looks like:

{
    "groupName": "some-group-name",
    "userIds": ["001", "002", "003"]
}

我的数据库中还有一个单独的用户节点.这是用户的样子:

I also have a separate node of users in my database. This is what a user looks like:

{
    "id": "001",
    "userName": "some-unique-username"
}

我想列出每个组及其成员.所以,它会是:

I want to list every single group and its members. So, it would be:

  • group1

  • group1

  • user1 id;用户 1 名称;
  • 用户 2 id;用户 2 名称;

group2

  • user3 id;user3 名称;
  • user4 id;用户 4 名称;

等等...

如何(如果有的话)获取这些组及其用户 ID 并通过 ID 查询用户并仅通过一个请求返回包含所有数据的单个 JSON?

How would it be possible (if at all) to fetch these groups and their user ids and also query for users by id and return a single JSON containing all the data only with one request?

现在我只是获取一些组并遍历每个组的 userIds 并分别为每个用户发送请求.我不是在问分页或简单的查询,我只是想获取每个组以及这些组中的用户.

Right now I'm just fetching some amount of groups and iterating over the userIds of each of them and sending a request for each user separately. I'm not asking about pagination or simple querying, I just want to get every group and the users inside those groups.

推荐答案

自己想出来的.

我需要做的是创建一个单独的解析器来获取每个组的成员:

What I needed to do was to create a separate resolver for fetching members of each group:

resolvers: {
    ...
    Group: {
        members: (group, _, context) => group.members.map(memberId => context.db.findUserById(memberId)
    }
    ...
}

父组对象作为第一个参数传递给解析器,因此当我查询时:

The parent group object is passed as the first argument to the resolver so when I query:

{
    groups(count: 10){
        name
        members {
            name
        }
    }
}

它返回前 10 个组的名称及其成员的名称.

It returns the names of the first 10 groups along with its members' names.

这篇关于一个请求中的 GraphQL 多个查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆