Class: GraphQL::Schema::Validator::AllValidator

Inherits:
GraphQL::Schema::Validator show all
Defined in:
lib/graphql/schema/validator/all_validator.rb

Overview

Use this to validate each member of an array value.

Examples:

validate format of all strings in an array


argument :handles, [String],
  validates: { all: { format: { with: /\A[a-z0-9_]+\Z/ } } }

multiple validators can be combined


argument :handles, [String],
  validates: { all: { format: { with: /\A[a-z0-9_]+\Z/ }, length: { maximum: 32 } } }

any type can be used


argument :choices, [Integer],
  validates: { all: { inclusion: { in: 1..12 } } }

Constant Summary

Constants included from EmptyObjects

EmptyObjects::EMPTY_ARRAY, EmptyObjects::EMPTY_HASH

Instance Attribute Summary

Attributes inherited from GraphQL::Schema::Validator

#validated

Instance Method Summary collapse

Methods inherited from GraphQL::Schema::Validator

from_config, install, #partial_format, #permitted_empty_value?, uninstall, validate!

Constructor Details

#initialize(validated:, allow_blank: false, allow_null: false, **validators) ⇒ AllValidator

Returns a new instance of AllValidator.



24
25
26
27
28
# File 'lib/graphql/schema/validator/all_validator.rb', line 24

def initialize(validated:, allow_blank: false, allow_null: false, **validators)
  super(validated: validated, allow_blank: allow_blank, allow_null: allow_null)

  @validators = Validator.from_config(validated, validators)
end

Instance Method Details

#validate(object, context, value) ⇒ Object



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
# File 'lib/graphql/schema/validator/all_validator.rb', line 30

def validate(object, context, value)
  return EMPTY_ARRAY if permitted_empty_value?(value)

  all_errors = EMPTY_ARRAY

  value.each do |subvalue|
    @validators.each do |validator|
      errors = validator.validate(object, context, subvalue)
      if errors &&
          (errors.is_a?(Array) && errors != EMPTY_ARRAY) ||
          (errors.is_a?(String))
        if all_errors.frozen? # It's empty
          all_errors = []
        end
        if errors.is_a?(String)
          all_errors << errors
        else
          all_errors.concat(errors)
        end
      end
    end
  end

  unless all_errors.frozen?
    all_errors.uniq!
  end

  all_errors
end