Suppose you have a web application that displays a list of posts, and for each post, you want to display the author's name and the number of comments on that post. You have the following GraphQL schema:
type Post { id: ID! title: String! authorId: ID! commentIds: [ID]! } type Author { id: ID! name: String! } type Comment { id: ID! text: String! } type Query { posts: [Post]! author(id: ID!): Author comments(ids: [ID]!): [Comment]! }
To display the list of posts with the author's name and the number of comments, you can send a batched query that retrieves the necessary data in a single request. Here's an example of such a query:
[ { "id": "1", "query": "query GetPost($id: ID!) { post(id: $id) { title author { name } comments { id } } }", "variables": { "id": "1" } }, { "id": "2", "query": "query GetAuthor($id: ID!) { author(id: $id) { name } }", "variables": { "id": "1" } }, { "id": "3", "query": "query GetComments($ids: [ID]!) { comments(ids: $ids) { text } }", "variables": { "ids": ["1", "2", "3"] } } ]
This batched query retrieves the post with ID "1", the author with ID "1", and the comments with IDs "1", "2", and "3". The response from the server will be an array of three objects, one for each query in the batch:
[ { "data": { "post": { "title": "My first post", "author": { "name": "John Doe" }, "comments": [ { "id": "1" }, { "id": "2" }, { "id": "3" } ] } } }, { "data": { "author": { "name": "John Doe" } } }, { "data": { "comments": [ { "text": "Great post!" }, { "text": "I disagree." }, { "text": "Could you clarify this point?" } ] } } ]
By using a batched query, you can reduce the number of round trips between the client and the server and improve the performance of your application.