Victor Mukherjee
Victor Mukherjee

Reputation: 11075

Graphql syntax for single query for same field with different parameters from an array

I am looking for something like the below pseudo query:

query users($ids: [String!]) {
 "id from $ids": getUser(id){
    id
    name
    dob
  } 
}

To get a response like:

data: {
 '039ccf5c-3070-4368-b790-0884669e759d': {id: '039ccf5c-3070-4368-b790-0884669e759d', name: 'u1', 'dob': 12-12-12'},
'139ccf5c-3070-4368-b790-0884669e759d': {id: '139ccf5c-3070-4368-b790-0884669e759d', name: 'u1', 'dob': 12-12-12'},
}

Is this possible?

Upvotes: 1

Views: 750

Answers (1)

Daniel Rearden
Daniel Rearden

Reputation: 84867

You can use aliases to query to the same field multiple times:

query users($id1: String!, $id2: String!) {
  user1: getUser(id: $id1) {
    ...UserFragment
  }
  user2: getUser(id: $id1) {
    ...UserFragment
  }
}

fragment UserFragment on User {
  id
  name
  dob
}

There are no control structures in GraphQL, so there's no way to loop through a value that is a list. If your list of IDs is of variable length, then you'll have to construct a query similar to the above programmatically, dynamically generating both the variable definitions and the aliased fields.

Upvotes: 2

Related Questions