Class: GraphQL::Schema::Directive::Constraint

Inherits:
GraphQL::Schema::Directive show all
Defined in:
lib/graphql/schema/directive/constraint.rb

Overview

Allows using @constraint as a directive to validate input data

This directive validates the input value.

Examples:

Generates @constraint directive and validates input length and patten

class LengthInput < GraphQL::Schema::InputObject
  argument :arg, String,
    directives: {
      GraphQL::Schema::Directive::Constraint => {
        minLength: 3,
        maxLength: 5,
        pattern: '[0-9a-zA-Z]*$',
      },
    }
end

Instance Method Summary collapse

Constructor Details

#initialize(owner, **arguments) ⇒ Constraint

Returns a new instance of Constraint.



49
50
51
52
# File 'lib/graphql/schema/directive/constraint.rb', line 49

def initialize(owner, **arguments)
  arguments.each { |a| add_validator(owner, a) } unless arguments[:without_validator]
  super
end

Instance Method Details

#add_validator(owner, argument) ⇒ Object



54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
# File 'lib/graphql/schema/directive/constraint.rb', line 54

def add_validator(owner, argument)
  case argument
  in [:minLength, minLength]
    owner.validates({ length: { minimum: minLength } })
  in [:maxLength, maxLength]
    owner.validates({ length: { maximum: maxLength } })
  in [:pattern, pattern]
    owner.validates({ format: { with: pattern } })
  in [:min, min]
    owner.validates({ numericality: { greater_than_or_equal_to: min } })
  in [:max, max]
    owner.validates({ numericality: { less_than_or_equal_to: max } })
  in [:exclusiveMin, exclusiveMin]
    owner.validates({ numericality: { greater_than: exclusiveMin } })
  in [:exclusiveMax, exclusiveMax]
    owner.validates({ numericality: { less_than: exclusiveMax } })
  else
    raise NotImplementedError("Given arguments are not implemented yet")
  end
end