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

查看:310
本文介绍了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;user1名称;
  • user2 ID;user2名称;

group2

  • user3 ID;user3名称;
  • user4 ID;user4名称;

以此类推...

怎么可能(如果有的话)获取这些组及其用户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天全站免登陆