Sha256: 4bc3114a32468808a20244eb06641d72e92ad8649c00e8bcc49c4d9f28149cc3

Contents?: true

Size: 1.12 KB

Versions: 2

Compression:

Stored size: 1.12 KB

Contents

# Scalars _can't_ have selections
# Objects _must_ have selections
class GraphQL::StaticValidation::FieldsHaveAppropriateSelections
  include GraphQL::StaticValidation::Message::MessageHelper

  def validate(context)
    context.visitor[GraphQL::Nodes::Field] << -> (node, parent)  {
      field_defn = context.field_definition
      validate_field_selections(node, field_defn, context.errors)
    }
  end

  private

  def validate_field_selections(ast_field, field_defn, errors)
    resolved_type = field_defn.type.kind.unwrap(field_defn.type)

    if resolved_type.kind.scalar? && ast_field.selections.any?
      error = message("Selections can't be made on scalars (field '#{ast_field.name}' returns #{resolved_type.name} but has selections [#{ast_field.selections.map(&:name).join(", ")}])", ast_field)
    elsif resolved_type.kind.object? && ast_field.selections.none?
      error = message("Objects must have selections (field '#{ast_field.name}' returns #{resolved_type.name} but has no selections)", ast_field)
    else
      error = nil
    end

    if !error.nil?
      errors << error
      GraphQL::Visitor::SKIP
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
graphql-0.3.0 lib/graph_ql/static_validation/rules/fields_have_appropriate_selections.rb
graphql-0.2.0 lib/graph_ql/static_validation/fields_have_appropriate_selections.rb