DEV Community

Discussion on: First dive into GraphQL Ruby

Collapse
 
mando75 profile image
Bryan Müller

We've been using GraphQL Ruby Pro in production for a couple years now. A tool that we've used to help prevent N+1 queries is JIT Preloader github.com/clio/jit_preloader

You can use it in a field resolver like so:

Types::UserType < Types::BaseType

# stuff
#
# 

  field :partners, [Types::PartnerType, null: true], null: true do
    argument :limit, Integer, description: "Limit records (default: 50, max: 50).", required: false
    argument :offset, Integer, description: "Offset by number of records, exceeding total record count will return 0 records.", required: false
    argument :order, String, description: "Order records by (created/updated_at_asc/desc).", required: false
  end

  def partners(**args)
    Resolvers::PartnersResolver.call(object.partners.jit_preload, args, context)
  end
end

JIT Preload will then figure out which associations to load down the query resolver chain. For more details I would check out their docs. It has been pretty handy and a great way for us to address the N+1 query problem with ActiveRecord.

It's also handy because it can be applied outside the context of GraphQL as well in somewhere like the service layer.

Collapse
 
camblan profile image
Julien Camblan

Thanks Bryan for the advice! JIT Preloader sounds really nice. I've browsed through the documentation and it seems much less verbose than BatchLoader which I'm using at the moment anyway. I'm going to start trying it out in preparation for the next version of our GraphQL API. If it answers my concerns, it should be much more convenient to maintain.