How to query for dynamic amount of aliases?

1.3k views Asked by At

Assume I have a GraphQL Schema like this:

Schema {
  user($id: ID) {
    id: ID
    name: String
  }
}

I know how to query for one user by his ID, and I could use aliases to query for several users like so:

GetSomeMore {
  john: user(id: "123") {
    name
  }
  mary: user(id: "321") {
    name
  }
}

However, assume I just have a list of user IDs, and would like to query for the names of each one of them. How would I write a query like that?

The approaches I can come up with is ether dynamically generating a query with aliases like user1, user2, etc., or implementing a users(ids: [ID]) edge on the server. But I feel like there should be a better solution. Is there?

(PS: my code examples might have syntax errors, I'm writing it more as pseudocode, to get my point across.)

2

There are 2 answers

3
marktani On BEST ANSWER

You could implement that functionality as part of your schema, for example with a id_in: [String] argument to the users query.

At Graphcool, we use the filter argument to expose functionality like this. For example, your query could be done like this:

query {
  allUsers(filter: {id_in: ["123", "321"]}) {
    id
    name
  }
}

results in

{
  "data": {
    "allUsers": [
      {
        "id": "123",
        "name": "John"
      },
      {
        "id": "321",
        "name": "Mary"
      }
    ]
  }
}

To read more about the filter argument check the documentation.

4
GG. On

I would go with your last proposition:

Schema {
  users($ids: [ID]) {
    id: ID
    name: String
  }
}

With a resolver like:

const users = async (root, { ids }) => await knex('users').whereIn('id', ids)

Note: I use + + to create my schema, my types and my resolvers.