Skip to content

Instantly share code, notes, and snippets.

@Grohden
Created June 23, 2022 20:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Grohden/4828350e26d330841ae257fac9886f0a to your computer and use it in GitHub Desktop.
Save Grohden/4828350e26d330841ae257fac9886f0a to your computer and use it in GitHub Desktop.
GQL ruby gem lookahead extra

The lookahead feature is exposed through an extra:

field :organizations, [Organization], extras: [:lookahead]

By declaring the lookahead extra we can use it to know which fields the client is asking for (through selects?):

def organizations(lookahead:)
    scope = Organization.all

    # :workers here refers to the gql field, lookahead doesn't know about your records.
    if lookahead.selects?(:workers) 
       scope = scope.includes(:workers, :other_dependant_relation_field)
    end

    scope
end

For the example above a gql query like

query Orgs {
  organization {
     id
  }
}

Would generate a db query like

SELECT * FROM organization

And a query for selecting the workers field like

query Orgs {
  organization {
     workers { id }
  }
}

Would generate something like this:

SELECT * FROM organization
SELECT * FROM workers WHERE workers.organization_id IN (1, 2, 3, 4, 5)

So lookahead can be used to avoid unneeded includes/optimizations where they're not needed 😄

(We can even use it to optimize selects for specific fields, but that's too much of a microoptimization)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment