Class: RuboCop::Cop::GraphQL::ContextWriteInType

Inherits:
Base
  • Object
show all
Defined in:
lib/rubocop/cop/graphql/context_write_in_type.rb

Overview

Detects writes to the context object within GraphQL types. Writing to context mutates shared state across the query execution, which can lead to unexpected behavior and makes code harder to reason about.

This cop is disabled by default.

Examples:

# bad
class UserType < BaseType
  field :name, String, null: false

  def name
    context[:current_user] = object.user
    object.name
  end
end

# bad
class UserType < BaseType
  field :name, String, null: false

  def name
    context.merge!(current_user: object.user)
    object.name
  end
end

# good
class UserType < BaseType
  field :name, String, null: false

  def name
    viewer = context[:current_user]
    object.name
  end
end

Constant Summary collapse

MSG =
"Avoid writing to `context` in GraphQL types. Mutating shared state can lead " \
"to unexpected behavior."
RESTRICT_ON_SEND =
i[[]= merge! store].freeze

Instance Method Summary collapse

Instance Method Details

#context_write?(node) ⇒ Object



50
51
52
# File 'lib/rubocop/cop/graphql/context_write_in_type.rb', line 50

def_node_matcher :context_write?, "(send (send nil? :context) {:[]= :merge! :store} ...)\n"

#on_send(node) ⇒ Object



54
55
56
57
58
# File 'lib/rubocop/cop/graphql/context_write_in_type.rb', line 54

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

  add_offense(node)
end