Sha256: 6f696b01f4a4ed579511a78b4b244e2a81daaeeb31e60fdd61c6126eb56fd541

Contents?: true

Size: 1.52 KB

Versions: 6

Compression:

Stored size: 1.52 KB

Contents

# frozen_string_literal: true

module Rails
  module GraphQL
    module Helpers
      # Helper that contains the main exceptions and validation process for a
      # value against a type
      module WithValidator
        delegate :ordinalize, to: 'ActiveSupport::Inflector'

        protected

          # Run the validation process with +value+ against +type+
          def validate_output!(value, type, checker: :null?, array: true)
            result = validate_null(value, checker)
            result ||= array? && array \
              ? validate_array(value) \
              : validate_type(value) \
              unless value.nil?

            return if result.blank?
            message, idx = result

            base_error = idx.present? \
              ? +"#{ordinalize(idx + 1)} value of the #{gql_name} #{type}" \
              : +"#{gql_name} #{type} value"

            raise InvalidValueError, +"The #{base_error} #{message}."
          end

        private

          def validate_array(value)
            return 'is not an array' unless value.is_a?(Enumerable)

            value.each_with_index do |val, idx|
              err = validate_null(val, :nullable?) || validate_type(val)
              return err, idx unless err.nil?
            end
          end

          def validate_null(value, checker = :null?)
            'can not be null' if value.nil? && !send(checker)
          end

          def validate_type(value)
            'is invalid' if leaf_type? && !type_klass.valid_output?(value)
          end
      end
    end
  end
end

Version data entries

6 entries across 6 versions & 1 rubygems

Version Path
rails-graphql-1.0.2 lib/rails/graphql/helpers/with_validator.rb
rails-graphql-1.0.1 lib/rails/graphql/helpers/with_validator.rb
rails-graphql-1.0.0 lib/rails/graphql/helpers/with_validator.rb
rails-graphql-1.0.0.rc2 lib/rails/graphql/helpers/with_validator.rb
rails-graphql-1.0.0.rc1 lib/rails/graphql/helpers/with_validator.rb
rails-graphql-1.0.0.beta lib/rails/graphql/helpers/with_validator.rb