Class: GraphQL::StaticValidation::Validator

Inherits:
Object
  • Object
show all
Defined in:
lib/graphql/static_validation/validator.rb

Overview

Initialized with a GraphQL::Schema, then it can validate Language::Nodes::Documentss based on that schema.

By default, it's used by Query

Examples:

Validate a query

validator = GraphQL::StaticValidation::Validator.new(schema: MySchema)
document = GraphQL.parse(query_string)
errors = validator.validate(document)

Instance Method Summary collapse

Constructor Details

#initialize(schema:, rules: GraphQL::StaticValidation::ALL_RULES) ⇒ Validator

Returns a new instance of Validator

Parameters:


15
16
17
18
# File 'lib/graphql/static_validation/validator.rb', line 15

def initialize(schema:, rules: GraphQL::StaticValidation::ALL_RULES)
  @schema = schema
  @rules = rules
end

Instance Method Details

#validate(query) ⇒ Array<Hash>

Validate query against the schema. Returns an array of message hashes.

Parameters:

Returns:

  • (Array<Hash>)

23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/graphql/static_validation/validator.rb', line 23

def validate(query)
  context = GraphQL::StaticValidation::ValidationContext.new(query)
  rewrite = GraphQL::InternalRepresentation::Rewrite.new

  # Put this first so its enters and exits are always called
  rewrite.validate(context)
  @rules.each do |rules|
    rules.new.validate(context)
  end

  context.visitor.visit

  {
    errors: context.errors,
    # If there were errors, the irep is garbage
    irep: context.errors.none? ? rewrite.operations : nil,
  }
end