Class: RuboCop::Cop::GraphQL::Overfetch

Inherits:
RuboCop::Cop show all
Defined in:
lib/rubocop/cop/graphql/overfetch.rb

Overview

Public: Rubocop for catching overfetched fields in ERB templates.

Instance Method Summary collapse

Instance Method Details

#field_aliases(name) ⇒ Object



48
49
50
51
52
53
54
55
56
57
58
# File 'lib/rubocop/cop/graphql/overfetch.rb', line 48

def field_aliases(name)
  names = Set.new

  names << name
  names << "#{name}?"

  names << underscore_name = ActiveSupport::Inflector.underscore(name)
  names << "#{underscore_name}?"

  names
end

#investigate(processed_source) ⇒ Object



14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# File 'lib/rubocop/cop/graphql/overfetch.rb', line 14

def investigate(processed_source)
  erb = File.read(processed_source.buffer.name)
  query, = ::GraphQL::Client::Erubis.extract_graphql_section(erb)
  return unless query

  aliases = {}
  fields = {}
  ranges = {}

  # TODO: Use GraphQL client parser
  document = ::GraphQL.parse(query.gsub(/::/, "__"))

  visitor = ::GraphQL::Language::Visitor.new(document)
  visitor[::GraphQL::Language::Nodes::Field] << ->(node, _parent) do
    name = node.alias || node.name
    fields[name] ||= 0
    field_aliases(name).each { |n| (aliases[n] ||= []) << name }
    ranges[name] ||= source_range(processed_source.buffer, node.line, 0)
  end
  visitor.visit

  send_methods(processed_source.ast).each do |node|
    _receiver, method_name, *_args = *node
    aliases.fetch(method_name.to_s, []).each do |field_name|
      fields[field_name] += 1
    end
  end

  fields.each do |field, count|
    next if count > 0
    add_offense(nil, ranges[field], "GraphQL field '#{field}' query but was not used in template.")
  end
end