Sha256: ff43d4f1c6b2df377d12b2c1cb5da70023c3e4c46c11cdd09211ce5343c4a589

Contents?: true

Size: 1.41 KB

Versions: 7

Compression:

Stored size: 1.41 KB

Contents

# frozen_string_literal: true
module GraphQL
  module StaticValidation
    class VariableDefaultValuesAreCorrectlyTyped
      include GraphQL::StaticValidation::Message::MessageHelper

      def validate(context)
        context.visitor[GraphQL::Language::Nodes::VariableDefinition] << ->(node, parent) {
          if !node.default_value.nil?
            validate_default_value(node, context)
          end
        }
      end

      def validate_default_value(node, context)
        value = node.default_value
        if node.type.is_a?(GraphQL::Language::Nodes::NonNullType)
          context.errors << message("Non-null variable $#{node.name} can't have a default value", node, context: context)
        else
          type = context.schema.type_from_ast(node.type)
          if type.nil?
            # This is handled by another validator
          else
            begin
              valid = context.valid_literal?(value, type)
            rescue GraphQL::CoercionError => err
              error_message = err.message
            rescue GraphQL::LiteralValidationError
              # noop, we just want to stop any LiteralValidationError from propagating
            end

            if !valid
              error_message ||= "Default value for $#{node.name} doesn't match type #{type}"
              context.errors << message(error_message, node, context: context)
            end
          end
        end
      end
    end
  end
end

Version data entries

7 entries across 7 versions & 1 rubygems

Version Path
graphql-1.8.18 lib/graphql/static_validation/rules/variable_default_values_are_correctly_typed.rb
graphql-1.8.17 lib/graphql/static_validation/rules/variable_default_values_are_correctly_typed.rb
graphql-1.8.16 lib/graphql/static_validation/rules/variable_default_values_are_correctly_typed.rb
graphql-1.8.15 lib/graphql/static_validation/rules/variable_default_values_are_correctly_typed.rb
graphql-1.8.14 lib/graphql/static_validation/rules/variable_default_values_are_correctly_typed.rb
graphql-1.8.13 lib/graphql/static_validation/rules/variable_default_values_are_correctly_typed.rb
graphql-1.8.12 lib/graphql/static_validation/rules/variable_default_values_are_correctly_typed.rb