Spring Boot GraphQL Tutorial #30 – DataLoader Key Context

Опубликовано: 01 Ноябрь 2024
на канале: Philip Starritt
3,763
29

The dreaded graphql N+1 problem gives most devs the creeps.

By default in GraphQL, a query resolver will resolve a field's nodes sequentially. When you have a list (see connection cursor video linked below) of nodes, It will resolve each node's fields sequentially. For example if you have 2 nodes with field X in the selection set. It will execute the query resolver first, then resolver for Node1 Field X followed by Node2 Field X. This is the N+1 problem.


We figured out how to solve the above dataloader n+1 problem in part 23:    • Spring Boot GraphQL Tutorial #23 - Da...  

BUT Now we have another problem!


What happens if we require some additional fields from the BankAccount (Context) inside the dataloader function? How do we pass them into the dataloader?


In this example, we may need to enrich the Balance response with another field contained the BankAccount. This final value would then be set into the dataloader's return Map.



To solve this problem, we can load the ID with a context into the dataloader. In this example, the context is BankAccount. The IDs mapped to Contexts are accessible inside the dataloader function via the BatchLoaderEnvironment#getKeyContexts. Unfortunately this returns a Map(Object, Object) instead of the preferred generic types, so we loose type safety. To get around this, we cast this to Map, then we pass the Map into our function with Map(UUID, BankAccount) defined as the method parameters.


But, why don't we just load the BankAccount into the dataloader?
This sounds good and easy - BUT If you do that, then we no-longer get the speed from the UUID hashmap lookups. So we always use the most efficient key possible.

Please check out the github graphql java dataloader docs for more detail and examples!


See you in the next video!
Cheers,
Philip

Spring Boot GraphQL Java: https://github.com/graphql-java-kicks...



GraphQL Java DataLoader: https://github.com/graphql-java/java-...
Mapped Batch DataLoader: https://github.com/graphql-java/java-...
GraphQL DataLoader from facebook: https://github.com/graphql/dataloader
GraphQL Connection Cursor Pagination Tutorial:    • Spring Boot GraphQL Tutorial #21 - Pa...