Lets say we have following graphql schema:
type Author : Object {
id: ID!
name: String,
books: [Book]
}
type Book : Object {
id: ID!
title: String
authorId: Int
author: Author
}
And then making a query like:
{
books: {
id
title
author { id name }
}
}
If, for example, we have 10 books, then we will end up with 10 author queries, as the resolve function will be called for each fetched book:
select id, name from author where id = 123
Instead of this we can execute all author queries as a single query:
select id, name from author where id in (123, 456, 789, 1011)
Is there some working solutions, best practices, techniques or something that can help to achieve this?
There are numerous optimization techniques you should consider when working with GraphQL servers, but the most common is the caching technique which returns persistent data, and also the batching technique which reduces the number of round trips your server makes to the database.
GraphQL can be overkillSince GraphQL is so complex and powerful, it can commonly be overkill for smaller applications. If you have a simple/straight-forward app in front of you, it will be easier to work with a REST API.
Dataloader is your answer, it has batching feature which means that it will queue all the ids. And only once its ready it will pull it as a batch Demo can be found here: https://youtu.be/UBGzsb2UkeY (Last 5 minutes in particular) Algorithem explained can be found here: https://youtu.be/OQTnXNCDywA
Enjoy :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With