Sha256: 550dfff88dfe48344266d70943240176eea4e9e84424303b829258212eec6fcd

Contents?: true

Size: 1.29 KB

Versions: 13

Compression:

Stored size: 1.29 KB

Contents

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

      def validate(context)
        context.visitor[GraphQL::Language::Nodes::Field] << -> (node, parent)  {
          return if context.skip_field?(node.name)
          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.unwrap

        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::Language::Visitor::SKIP
        end
      end
    end
  end
end

Version data entries

13 entries across 13 versions & 1 rubygems

Version Path
graphql-0.17.2 lib/graphql/static_validation/rules/fields_have_appropriate_selections.rb
graphql-0.17.1 lib/graphql/static_validation/rules/fields_have_appropriate_selections.rb
graphql-0.17.0 lib/graphql/static_validation/rules/fields_have_appropriate_selections.rb
graphql-0.16.1 lib/graphql/static_validation/rules/fields_have_appropriate_selections.rb
graphql-0.16.0 lib/graphql/static_validation/rules/fields_have_appropriate_selections.rb
graphql-0.15.3 lib/graphql/static_validation/rules/fields_have_appropriate_selections.rb
graphql-0.15.2 lib/graphql/static_validation/rules/fields_have_appropriate_selections.rb
graphql-0.14.2 lib/graphql/static_validation/rules/fields_have_appropriate_selections.rb
graphql-0.15.1 lib/graphql/static_validation/rules/fields_have_appropriate_selections.rb
graphql-0.15.0 lib/graphql/static_validation/rules/fields_have_appropriate_selections.rb
graphql-0.14.1 lib/graphql/static_validation/rules/fields_have_appropriate_selections.rb
graphql-0.14.0 lib/graphql/static_validation/rules/fields_have_appropriate_selections.rb
graphql-0.13.0 lib/graphql/static_validation/rules/fields_have_appropriate_selections.rb