class GraphQL::StaticValidation::DirectivesAreInValidLocations

Constants

LOCATION_MESSAGE_NAMES
SIMPLE_LOCATIONS
SIMPLE_LOCATION_NODES

Public Instance Methods

validate(context) click to toggle source
# File lib/graphql/static_validation/rules/directives_are_in_valid_locations.rb, line 7
def validate(context)
  directives = context.schema.directives

  context.visitor[Nodes::Directive] << ->(node, parent) {
    validate_location(node, parent, directives, context)
  }
end

Private Instance Methods

assert_includes_location(directive_defn, directive_ast, required_location, context) click to toggle source
# File lib/graphql/static_validation/rules/directives_are_in_valid_locations.rb, line 50
def assert_includes_location(directive_defn, directive_ast, required_location, context)
  if !directive_defn.locations.include?(required_location)
    location_name = LOCATION_MESSAGE_NAMES[required_location]
    allowed_location_names = directive_defn.locations.map { |loc| LOCATION_MESSAGE_NAMES[loc] }
    context.errors << message("'@#{directive_defn.name}' can't be applied to #{location_name} (allowed: #{allowed_location_names.join(", ")})", directive_ast, context: context)
  end
end
validate_location(ast_directive, ast_parent, directives, context) click to toggle source
# File lib/graphql/static_validation/rules/directives_are_in_valid_locations.rb, line 36
def validate_location(ast_directive, ast_parent, directives, context)
  directive_defn = directives[ast_directive.name]
  case ast_parent
  when Nodes::OperationDefinition
    required_location = GraphQL::Directive.const_get(ast_parent.operation_type.upcase)
    assert_includes_location(directive_defn, ast_directive, required_location, context)
  when *SIMPLE_LOCATION_NODES
    required_location = SIMPLE_LOCATIONS[ast_parent.class]
    assert_includes_location(directive_defn, ast_directive, required_location, context)
  else
    context.errors << message("Directives can't be applied to #{ast_parent.class.name}s", ast_directive, context: context)
  end
end