Class: GraphQL::Schema::Validator::RequiredValidator

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

Overview

Use this validator to require one of the named arguments to be present. Or, use Arrays of symbols to name a valid set of arguments.

(This is for specifying mutually exclusive sets of arguments.)

Examples:

Require exactly one of these arguments


field :update_amount, IngredientAmount, null: false do
  argument :ingredient_id, ID, required: true
  argument :cups, Integer, required: false
  argument :tablespoons, Integer, required: false
  argument :teaspoons, Integer, required: true
  validates required: { one_of: [:cups, :tablespoons, :teaspoons] }
end

Require one of these sets of arguments


field :find_object, Node, null: true do
  argument :node_id, ID, required: false
  argument :object_type, String, required: false
  argument :object_id, Integer, required: false
  # either a global `node_id` or an `object_type`/`object_id` pair is required:
  validates required: { one_of: [:node_id, [:object_type, :object_id]] }
end

Constant Summary

Constants included from FindInheritedValue::EmptyObjects

FindInheritedValue::EmptyObjects::EMPTY_ARRAY, FindInheritedValue::EmptyObjects::EMPTY_HASH

Instance Attribute Summary

Attributes inherited from GraphQL::Schema::Validator

#validated

Instance Method Summary collapse

Methods inherited from GraphQL::Schema::Validator

#apply, from_config, install, #partial_format, uninstall, validate!

Constructor Details

#initialize(one_of:, message: "%{validated} has the wrong arguments", **default_options) ⇒ RequiredValidator

Returns a new instance of RequiredValidator.

Parameters:

  • one_of (Symbol, Array<Symbol>)

    An argument, or a list of arguments, that represents a valid set of inputs for this field

  • message (String) (defaults to: "%{validated} has the wrong arguments")


34
35
36
37
38
# File 'lib/graphql/schema/validator/required_validator.rb', line 34

def initialize(one_of:, message: "%{validated} has the wrong arguments", **default_options)
  @one_of = one_of
  @message = message
  super(**default_options)
end

Instance Method Details

#validate(_object, _context, value) ⇒ Object



40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
# File 'lib/graphql/schema/validator/required_validator.rb', line 40

def validate(_object, _context, value)
  matched_conditions = 0

  @one_of.each do |one_of_condition|
    case one_of_condition
    when Symbol
      if value.key?(one_of_condition)
        matched_conditions += 1
      end
    when Array
      if one_of_condition.all? { |k| value.key?(k) }
        matched_conditions += 1
        break
      end
    else
      raise ArgumentError, "Unknown one_of condition: #{one_of_condition.inspect}"
    end
  end

  if matched_conditions == 1
    nil # OK
  else
    @message
  end
end