Class: Rails::GraphQL::Request::Errors

Inherits:
Object
  • Object
show all
Includes:
Enumerable
Defined in:
lib/rails/graphql/request/errors.rb

Overview

GraphQL Request Errors

This class is inspired by ActiveModel::Errors. The idea is to hold all the errors that happened during the execution of a request. It also helps to export such information to the result object.

Instance Method Summary collapse

Constructor Details

#initialize(request) ⇒ Errors

Returns a new instance of Errors.



16
17
18
19
# File 'lib/rails/graphql/request/errors.rb', line 16

def initialize(request)
  @request = request
  @items   = []
end

Instance Method Details

#add(message, line: nil, col: nil, path: nil, **extra) ⇒ Object

Add message to the list of errors. Any other keyword argument will be used on set on the :extensions part.

Options

  • :line - The line associated with the error.

  • :col - The column associated with the error.

  • :path - The path of the field that generated the error.



38
39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/rails/graphql/request/errors.rb', line 38

def add(message, line: nil, col: nil, path: nil, **extra)
  item = { 'message' => message }

  item['locations'] = extra.delete(:locations)
  item['locations'] ||= [{ line: line.to_i, column: col.to_i }] \
    if line.present? && col.present?

  item['path'] = path if path.present? && path.is_a?(::Array)
  item['extensions'] = extra.deep_stringify_keys if extra.present?
  item['locations']&.map!(&:stringify_keys)

  @items << item.compact
end

#cache_dumpObject

Dump the necessary information from errors to a cached operation



53
54
55
# File 'lib/rails/graphql/request/errors.rb', line 53

def cache_dump
  @items.select { |item| item.dig('extensions', 'stage') == 'organize' }
end

#cache_load(data) ⇒ Object

Load the necessary information from a cached request data



58
59
60
# File 'lib/rails/graphql/request/errors.rb', line 58

def cache_load(data)
  @items += data
end

#reset!Object



21
22
23
# File 'lib/rails/graphql/request/errors.rb', line 21

def reset!
  @items = []
end

#to_aObject

Return a deep duplicated version of the items



26
27
28
# File 'lib/rails/graphql/request/errors.rb', line 26

def to_a
  @items.deep_dup
end