Search code examples
graphqlgraphql-java

GraphQL - Difference between using alias versus multiple query objects when doing batch queries


I'm fairly new to GraphQL, so please correct me if I'm wrong where need be. I'm wondering what would be the best way, or the most appropriate way, to execute batch queries in a single request. I've seen examples that do this:

[
  {
    query: "query(param1)"
  },
  {
    query: "query(param2)"
  }
]

Or examples that use aliases to accomplish the same thing:

query {
  alias1: resolver1(param1)
  alias2: resolver2(param2)
}

In my opinion, I think the aliases is the more appropriate option as it's a single query and within that query I'm requesting data with different parameters. So, between the two options above, what would be the more appropriate option for executing batch queries in GraphQL, and why? Thanks!


Solution

  • Batching operations by sending an array of them to the server is something that's not supported by all libraries. This is not a feature of GraphQL as much as just a convenient feature supported by some server libraries. On the other hand, including multiple root-level fields in a single operation is supported by all GraphQL servers. So, if you're anticipating the backend you are querying to possibly change in the future, you may want to use Option #2 over Option #1 to avoid having to potentially refactor your code in the future.

    On the other hand, batching is often desirable because it allows you to mix operation types. While you can include any number of root-level fields in a single operation, only one operation may be executed at a time -- that means you can't mix queries and mutations with Option #2. If this is something you need to do, batching is the only way to achieve it in a single request (assuming your server supports it).