debian-mirror-gitlab/app/graphql/resolvers/concerns/looks_ahead.rb

78 lines
1.9 KiB
Ruby
Raw Normal View History

2020-06-23 00:09:42 +05:30
# frozen_string_literal: true
module LooksAhead
extend ActiveSupport::Concern
included do
2021-01-29 00:20:46 +05:30
extras [:lookahead]
2020-06-23 00:09:42 +05:30
attr_accessor :lookahead
end
def resolve(**args)
self.lookahead = args.delete(:lookahead)
resolve_with_lookahead(**args)
end
def apply_lookahead(query)
2021-04-29 21:17:54 +05:30
all_preloads = (unconditional_includes + filtered_preloads).uniq
2020-06-23 00:09:42 +05:30
2021-03-08 18:12:59 +05:30
return query if all_preloads.empty?
2020-06-23 00:09:42 +05:30
2021-03-08 18:12:59 +05:30
query.preload(*all_preloads) # rubocop: disable CodeReuse/ActiveRecord
2020-06-23 00:09:42 +05:30
end
private
def unconditional_includes
[]
end
def preloads
{}
end
2022-11-25 23:54:43 +05:30
def nested_preloads
{}
end
2021-04-29 21:17:54 +05:30
def filtered_preloads
2022-10-11 01:57:18 +05:30
nodes = node_selection
2023-03-04 22:38:38 +05:30
return [] unless nodes&.selected?
2022-10-11 01:57:18 +05:30
selected_fields = nodes.selections.map(&:name)
2022-11-25 23:54:43 +05:30
root_level_preloads = preloads_from_node_selection(selected_fields, preloads)
2021-04-29 21:17:54 +05:30
2022-11-25 23:54:43 +05:30
root_level_preloads + nested_filtered_preloads(nodes, selected_fields)
end
def nested_filtered_preloads(nodes, selected_root_fields)
return [] if nested_preloads.empty?
nested_preloads.each_with_object([]) do |(root_field, fields), result|
next unless selected_root_fields.include?(root_field)
selected_fields = nodes.selection(root_field).selections.map(&:name)
result << preloads_from_node_selection(selected_fields, fields)
end.flatten
end
def preloads_from_node_selection(selected_fields, fields)
fields.each_with_object([]) do |(field, requirements), result|
result << requirements if selected_fields.include?(field)
end.flatten
2021-04-29 21:17:54 +05:30
end
2023-03-04 22:38:38 +05:30
def node_selection(selection = lookahead)
return selection unless selection&.selected?
return selection.selection(:edges).selection(:node) if selection.selects?(:edges)
2020-06-23 00:09:42 +05:30
2023-03-04 22:38:38 +05:30
# Will return a NullSelection object if :nodes is not a selection. This
# is better than returning nil as we can continue chaining selections on
# without raising errors.
selection.selection(:nodes)
2020-06-23 00:09:42 +05:30
end
end