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)