8
votes

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?

2

2 Answers

10
votes

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 :)

5
votes

DataLoader is a great database-agnostic solution. If you're using SQL, Join Monster is more tailored for relational DBs and will even translate the GraphQL queries to SQL directly with a single round-trip. Another alternative is graph-joiner.