Closed bgentry closed 6 years ago
I guess #6 is basically a solution to this?
Hey, @bgentry!
Thanks for opening the issue. Yes, ideally, #6 will allow specifying custom keys. With your example it may look something like:
BatchLoader.for(...).batch(key: @klass.to_s, cache: false) do |ids, loader|
...
end
We added a support for passing a key
argument in the 1.2.0
version (#12) 🎉
BatchLoader.for(1).batch(key: klass) do |ids, loader|
klass.where(id: ids, org: parent.org).all.each do |child|
loader.call(child.id, child)
end
end
I tried to abstract out my BatchLoader calls a bit to DRY them up. In my GraphQL resolvers, I started using these field declarations:
With a
BatchLoadResolver
that would do the common work of loading a many:1 association:This same loading code was working fine when I had the
BatchLoader
blocks defined individually for each field. However, when doing the above, all of my objects' IDs would get mixed together into a single batch (rather than a batch for each type of object).It quickly became obvious that with a simple call like
BatchLoader.for(object_id)
there was clearly no way for this gem to distinguish between types of objects it would have to load. After some digging, I found the implementation call tosource_location
, which sets up a hash key for loaders based on where the loading block was defined. That makes sense given the minimal info I'm passingBatchLoader
when executing it, but it does limit the ways this library can be used.You may not consider this a bug, but I think you might at least want to make this more obvious in the readme. I suspect others will run into the same situation.
If this is something you care to support, maybe there could be another way to choose a hash key.