2020-06-05 21:08:27 +00:00
|
|
|
# frozen_string_literal: true
|
|
|
|
|
|
|
|
module LooksAhead
|
|
|
|
extend ActiveSupport::Concern
|
|
|
|
|
|
|
|
included do
|
2020-11-17 12:09:15 +00:00
|
|
|
extras [:lookahead]
|
2020-06-05 21:08:27 +00:00
|
|
|
attr_accessor :lookahead
|
|
|
|
end
|
|
|
|
|
|
|
|
def resolve(**args)
|
|
|
|
self.lookahead = args.delete(:lookahead)
|
|
|
|
|
|
|
|
resolve_with_lookahead(**args)
|
|
|
|
end
|
|
|
|
|
|
|
|
def apply_lookahead(query)
|
2021-04-09 12:09:12 +00:00
|
|
|
all_preloads = (unconditional_includes + filtered_preloads).uniq
|
2020-06-05 21:08:27 +00:00
|
|
|
|
2020-12-21 12:10:22 +00:00
|
|
|
return query if all_preloads.empty?
|
2020-06-05 21:08:27 +00:00
|
|
|
|
2020-12-21 12:10:22 +00:00
|
|
|
query.preload(*all_preloads) # rubocop: disable CodeReuse/ActiveRecord
|
2020-06-05 21:08:27 +00:00
|
|
|
end
|
|
|
|
|
|
|
|
private
|
|
|
|
|
|
|
|
def unconditional_includes
|
|
|
|
[]
|
|
|
|
end
|
|
|
|
|
|
|
|
def preloads
|
|
|
|
{}
|
|
|
|
end
|
|
|
|
|
2021-04-09 12:09:12 +00:00
|
|
|
def filtered_preloads
|
|
|
|
selection = node_selection
|
|
|
|
|
|
|
|
preloads.each.flat_map do |name, requirements|
|
|
|
|
selection&.selects?(name) ? requirements : []
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
2020-06-05 21:08:27 +00:00
|
|
|
def node_selection
|
|
|
|
return unless lookahead
|
|
|
|
|
|
|
|
if lookahead.selects?(:nodes)
|
|
|
|
lookahead.selection(:nodes)
|
|
|
|
elsif lookahead.selects?(:edges)
|
2020-09-04 09:08:38 +00:00
|
|
|
lookahead.selection(:edges).selection(:node)
|
2020-06-05 21:08:27 +00:00
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|