When implemented a GraphQL API using GraphQL Ruby it is beneficial to ensure that executed queries don’t trigger any N+1 query problems.
One (of many) solutions to this is graphql-batch which provides a means of delcaring loaders to perform batched execution, avoding N+1 query problems.
A record and assocation loader is provided by default and these perform their jobs admirably, though alone they do not cover the gamut of N+1 issues that can be encountered.
In this post we’ll address the issue of counting generically using
CountLoader, and more explicitly associations using
The following example type if fetched multiple times in a query (e.g. as a collection) would cause multiple queries in counting:
We can resolve this issue by implementing a
CountLoader and updating the typing accordingly.
CountLoader above the multiple queries as a result of counting have been resolved. As can be seen the structure of
CountLoader is very similar to the provided
Counting ActiveRecord associations
Reddit user u/Owumaro suggested using an ActiveRecord association name rather than having to specify the join model and foriegn key back.
AssociationCountLoader reflects on the provided relationship to alleviate the need for specifying these extra implementation details (it should be less britle).
Types::UserType changes to:
2021-04-14 Update: Implementations of the loaders shown here are being maintained at https://github.com/jamesbrooks/graphql-batch-loaders