class GraphQL::StaticValidation::Validator

Initialized with a {GraphQL::Schema}, then it can validate {GraphQL::Language::Nodes::Documents}s based on that schema.

By default, it's used by {GraphQL::Query}

@example Validate a query

validator = GraphQL::StaticValidation::Validator.new(schema: MySchema)
query = GraphQL::Query.new(MySchema, query_string)
errors = validator.validate(query)[:errors]

Public Class Methods

new(schema:, rules: GraphQL::StaticValidation::ALL_RULES) click to toggle source

@param schema [GraphQL::Schema] @param rules [Array<#validate(context)>] a list of rules to use when validating

# File lib/graphql/static_validation/validator.rb, line 16
def initialize(schema:, rules: GraphQL::StaticValidation::ALL_RULES)
  @schema = schema
  @rules = rules
end

Public Instance Methods

validate(query, validate: true) click to toggle source

Validate `query` against the schema. Returns an array of message hashes. @param query [GraphQL::Query] @return [Array<Hash>]

# File lib/graphql/static_validation/validator.rb, line 24
def validate(query, validate: true)
  query.trace("validate", { validate: validate, query: query }) do
    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)

    # If the caller opted out of validation, don't attach these
    if validate
      @rules.each do |rules|
        rules.new.validate(context)
      end
    end

    context.visitor.visit
    rewrite_result = rewrite.document

    # Post-validation: allow validators to register handlers on rewritten query nodes
    GraphQL::InternalRepresentation::Visit.visit_each_node(rewrite_result.operation_definitions, context.each_irep_node_handlers)

    {
      errors: context.errors,
      # If there were errors, the irep is garbage
      irep: context.errors.any? ? nil : rewrite_result,
    }
  end
end