Class: Decidim::Api::Errors::AttributeValidationError

Inherits:
GraphQL::ExecutionError
  • Object
show all
Defined in:
lib/decidim/api/errors/attribute_validation_error.rb

Instance Method Summary collapse

Constructor Details

#initialize(messages, ast_node: nil, options: nil, extensions: nil) ⇒ AttributeValidationError

Returns a new instance of AttributeValidationError.



7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# File 'lib/decidim/api/errors/attribute_validation_error.rb', line 7

def initialize(messages, ast_node: nil, options: nil, extensions: nil)
  @ast_node = ast_node
  @options = options
  @extensions = extensions

  @messages = messages

  message_str =
    if messages.is_a?(ActiveModel::Errors)
      messages.full_messages.join(", ")
    elsif messages.is_a?(Array)
      messages.map { |a| a[:message] }.join(", ")
    else
      messages.to_s
    end
  super(message_str)
end

Instance Method Details

#messageObject



64
65
66
67
68
69
# File 'lib/decidim/api/errors/attribute_validation_error.rb', line 64

def message
  return @messages.full_messages.join(", ") if @messages.is_a?(ActiveModel::Errors)
  return @messages.map { |a| [a[:path].last, a[:message]].join(": ") }.join(", ") if @messages.is_a?(Array)

  @messages.to_s
end

#to_hObject



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
57
58
59
60
61
62
# File 'lib/decidim/api/errors/attribute_validation_error.rb', line 25

def to_h
  hash = {}
  if @messages.is_a?(ActiveModel::Errors)
    hash["message"] = @messages.map do |error|
      # This is the GraphQL argument which corresponds to the validation error:
      local_path = ["attributes", error.attribute.to_s.camelize(:lower)]
      {
        path: local_path,
        message: error.message
      }
    end
  end

  hash["message"] = @messages if @messages.is_a?(Array)

  if ast_node
    hash["locations"] = [
      {
        "line" => ast_node.line,
        "column" => ast_node.col
      }
    ]
  end

  hash["path"] = path if path

  hash.merge!(options) if options

  if extensions
    hash["extensions"] = extensions.transform_keys do |(key, value), ext|
      ext[key.to_s] = value
    end
  end

  hash.merge!({ "extensions" => { "code" => "ATTRIBUTE_VALIDATION_ERROR" } })

  hash
end