summaryrefslogtreecommitdiff
path: root/rubocop/cop/graphql/descriptions.rb
blob: b4e00dfe33618ce67da8e13135c19d34e51de023 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
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
47
48
49
50
51
52
53
54
55
56
# frozen_string_literal: true

# This cop checks for missing GraphQL field descriptions.
#
# @example
#
#   # bad
#   class AwfulClass
#     field :some_field, GraphQL::STRING_TYPE
#   end
#
#   class TerribleClass
#     argument :some_argument, GraphQL::STRING_TYPE
#   end
#
#   # good
#   class GreatClass
#     argument :some_field,
#       GraphQL::STRING_TYPE,
#       description: "Well described - a superb description"
#
#     field :some_field,
#       GraphQL::STRING_TYPE,
#       description: "A thorough and compelling description"
#   end

module RuboCop
  module Cop
    module Graphql
      class Descriptions < RuboCop::Cop::Cop
        MSG = 'Please add a `description` property.'

        # ability_field and permission_field set a default description.
        def_node_matcher :fields, <<~PATTERN
          (send nil? :field $...)
        PATTERN

        def_node_matcher :arguments, <<~PATTERN
          (send nil? :argument $...)
        PATTERN

        def_node_matcher :has_description?, <<~PATTERN
          (hash <(pair (sym :description) _) ...>)
        PATTERN

        def on_send(node)
          matches = fields(node) || arguments(node)

          return if matches.nil?

          add_offense(node, location: :expression) unless has_description?(matches.last)
        end
      end
    end
  end
end