Adam
Adam

Reputation: 3518

How to create a graphql query that uses the same query multiple times

Given query

query user($id: Int!) {
  getUser(id: $id) {
    id
    name
  }
}

I'd like to grab multiple users and get them returned as an array ex: const users = [1, 2, 3, 5]

I it possible to query this from client, or do I need to define new Query on the server?

I am using Apollo with React btw.

Upvotes: 2

Views: 1663

Answers (2)

Michel Floyd
Michel Floyd

Reputation: 20227

Adding to @Jonathan's answer:

If you want to generalize to "give me an array of users based on an array of ids and you have the ability to add a query to the server, then define a new mutation:

query getUsersFromIds(ids: [ID!]!) [User]

Otherwise there is no generalized looping construct in GraphQL.

Upvotes: 1

Jonathan Wieben
Jonathan Wieben

Reputation: 671

Ideally, this is a problem best solved by extending the schema with a getUsers query.

As a workaround, you can use aliases to make multiple queries within a single query.

query users($id1: Int!, $id2: Int!, $id3: Int!) {
  user1: getUser(id: $id1) {
    id
    name
  }
  user2: getUser(id: $id2) {
    id
    name
  }
  user3: getUser(id: $id3) {
    id
    name
  }
}

Upvotes: 2

Related Questions