Class: RuboCop::Cop::GraphQL::FieldHashKey

Inherits:
Base
  • Object
show all
Extended by:
AutoCorrector
Includes:
RangeHelp, GraphQL::NodePattern
Defined in:
lib/rubocop/cop/graphql/field_hash_key.rb

Overview

This cop prevents defining unnecessary resolver methods in cases

when :hash_key option can be used

Examples:

# good

class Types::UserType < Types::BaseObject
  field :phone, String, null: true, hash_key: :home_phone
end

# bad

class Types::UserType < Types::BaseObject
  field :phone, String, null: true

  def phone
    object[:home_phone]
  end
end

Constant Summary collapse

MSG =
"Use hash_key: %<hash_key>p"
RESTRICT_ON_SEND =
%i[field].freeze

Instance Method Summary collapse

Methods included from GraphQL::NodePattern

#argument?, #field?, #field_definition?, #field_definition_with_body?

Instance Method Details

#hash_key_to_use(node) ⇒ Object



32
33
34
35
36
37
38
39
40
41
# File 'lib/rubocop/cop/graphql/field_hash_key.rb', line 32

def_node_matcher :hash_key_to_use, <<~PATTERN
  (def
    _
    (args)
    (send
      (send nil? :object) :[]
      ({sym str} $_)
    )
  )
PATTERN

#on_send(node) ⇒ Object



46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
# File 'lib/rubocop/cop/graphql/field_hash_key.rb', line 46

def on_send(node)
  return unless field_definition?(node)

  field = RuboCop::GraphQL::Field.new(node)
  method_definition = resolver_method_definition_for(field)

  suggested_hash_key_name = hash_key_to_use(method_definition)

  return if suggested_hash_key_name.nil?
  return if conflict?(suggested_hash_key_name)

  add_offense(node, message: message(suggested_hash_key_name)) do |corrector|
    autocorrect(corrector, node)
  end
end