Class: GraphQL::Schema::InputObject

Inherits:
Member
  • Object
show all
Extended by:
Forwardable, Member::HasArguments, Member::HasArguments::ArgumentObjectLoader, Member::HasValidators, Member::ValidatesInput
Includes:
Dig
Defined in:
lib/graphql/schema/input_object.rb

Defined Under Namespace

Classes: ArgumentsAreRequiredError

Constant Summary collapse

INVALID_OBJECT_MESSAGE =

:nodoc:

"Expected %{object} to be a key-value object."

Constants included from Member::HasArguments

Member::HasArguments::NO_ARGUMENTS

Constants included from EmptyObjects

EmptyObjects::EMPTY_ARRAY, EmptyObjects::EMPTY_HASH

Constants included from Member::GraphQLTypeNames

Member::GraphQLTypeNames::Boolean, Member::GraphQLTypeNames::ID, Member::GraphQLTypeNames::Int

Instance Attribute Summary collapse

Attributes included from Member::BaseDSLMethods

#default_graphql_name, #graphql_name

Attributes included from Member::RelayShortcuts

#connection_type, #connection_type_class, #edge_type, #edge_type_class

Attributes included from Member::HasAstNode

#ast_node

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Member::HasArguments

add_argument, all_argument_definitions, any_arguments?, argument, argument_class, arguments_statically_coercible?, coerce_arguments, extended, get_argument, included, own_arguments, remove_argument, validate_directive_argument

Methods included from Member::HasArguments::ArgumentObjectLoader

authorize_application_object, load_and_authorize_application_object, load_application_object, load_application_object_failed, object_from_id

Methods included from Member::ValidatesInput

coerce_isolated_input, coerce_isolated_result, valid_input?, valid_isolated_input?, validate_input

Methods included from Member::HasValidators

extended, validates, validators

Methods included from Dig

#dig

Methods included from Member::BaseDSLMethods

#authorized?, #comment, #default_relay?, #description, #introspection, #introspection?, #mutation, #visible?

Methods included from FindInheritedValue

extended, included

Methods included from Member::BaseDSLMethods::ConfigurationExtension

#inherited

Methods included from Member::TypeSystemHelpers

#kind, #list?, #non_null?, #to_list_type, #to_non_null_type, #to_type_signature

Methods included from Member::Scoped

#inherited, #reauthorize_scoped_objects, #scope_items

Methods included from Member::HasPath

#path

Methods included from Member::HasAstNode

extended, #inherited

Methods included from Member::HasDirectives

add_directive, #directive, #directives, extended, get_directives, #inherited, #remove_directive, remove_directive

Constructor Details

#initialize(arguments, ruby_kwargs:, context:, defaults_used:) ⇒ InputObject

Returns a new instance of InputObject.



35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# File 'lib/graphql/schema/input_object.rb', line 35

def initialize(arguments, ruby_kwargs:, context:, defaults_used:)
  @context = context
  @ruby_style_hash = ruby_kwargs
  @arguments = arguments
  # Apply prepares, not great to have it duplicated here.
  arg_defns = context ? context.types.arguments(self.class) : self.class.arguments(context).each_value
  arg_defns.each do |arg_defn|
    ruby_kwargs_key = arg_defn.keyword
    if @ruby_style_hash.key?(ruby_kwargs_key)
      # Weirdly, procs are applied during coercion, but not methods.
      # Probably because these methods require a `self`.
      if arg_defn.prepare.is_a?(Symbol) || context.nil?
        prepared_value = arg_defn.prepare_value(self, @ruby_style_hash[ruby_kwargs_key], context: context)
        overwrite_argument(ruby_kwargs_key, prepared_value)
      end
    end
  end
end

Instance Attribute Details

#arguments ⇒ Object (readonly)

Returns

  • GraphQL::Execution::Interpereter::Arguments — The underlying arguments instance


30
31
32
# File 'lib/graphql/schema/input_object.rb', line 30

def arguments
  @arguments
end

#context ⇒ Object (readonly)

Returns

  • GraphQL::Query::Context — The context for this query


26
27
28
# File 'lib/graphql/schema/input_object.rb', line 26

def context
  @context
end

Class Method Details

.argument(*args, **kwargs, &block) ⇒ Object



158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
# File 'lib/graphql/schema/input_object.rb', line 158

def argument(*args, **kwargs, &block)
  args = args #: untyped
  argument_defn = super(*args, **kwargs, &block)
  if one_of?
    if argument_defn.type.non_null?
      raise ArgumentError, "Argument '#{argument_defn.path}' must be nullable because it is part of a OneOf type, add `required: false`."
    end
    if argument_defn.default_value?
      raise ArgumentError, "Argument '#{argument_defn.path}' cannot have a default value because it is part of a OneOf type, remove `default_value: ...`."
    end
  end
  # Add a method access
  suppress_redefinition_warning do
    define_accessor_method(argument_defn.keyword)
  end
  argument_defn
end

.arguments(context = GraphQL::Query::NullContext.instance, require_defined_arguments = true) ⇒ Object



310
311
312
313
314
315
# File 'lib/graphql/schema/input_object.rb', line 310

def arguments(context = GraphQL::Query::NullContext.instance, require_defined_arguments = true)
  if require_defined_arguments && !has_no_arguments? && !any_arguments?
    warn(GraphQL::Schema::InputObject::ArgumentsAreRequiredError.new(self).message + "\n\nThis will raise an error in a future GraphQL-Ruby version.")
  end
  super(context, false)
end

.authorized?(obj, value, ctx) ⇒ Boolean

Returns:



131
132
133
134
135
136
137
138
139
140
141
142
143
# File 'lib/graphql/schema/input_object.rb', line 131

def authorized?(obj, value, ctx)
  # Authorize each argument (but this doesn't apply if `prepare` is implemented):
  if value.respond_to?(:key?)
    ctx.types.arguments(self).each do |input_obj_arg|
      if value.key?(input_obj_arg.keyword) &&
        !input_obj_arg.authorized?(obj, value[input_obj_arg.keyword], ctx)
        return false
      end
    end
  end
  # It didn't early-return false:
  true
end

.authorizes?(ctx) ⇒ Boolean

Returns:



127
128
129
# File 'lib/graphql/schema/input_object.rb', line 127

def authorizes?(ctx)
  self.method(:authorized?).owner != GraphQL::Schema::InputObject
end

.coerce_input(value, ctx) ⇒ Object



247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
# File 'lib/graphql/schema/input_object.rb', line 247

def coerce_input(value, ctx)
  if value.nil?
    return nil
  end

  arguments = coerce_arguments(nil, value, ctx)

  ctx.query.after_lazy(arguments) do |resolved_arguments|
    if resolved_arguments.is_a?(GraphQL::Error)
      raise resolved_arguments
    else
      self.new(resolved_arguments, ruby_kwargs: resolved_arguments.keyword_arguments, context: ctx, defaults_used: nil)
    end
  end
end

.coerce_result(value, ctx) ⇒ Object

It's funny to think of a result of an input object. This is used for rendering the default value in introspection responses.



265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
# File 'lib/graphql/schema/input_object.rb', line 265

def coerce_result(value, ctx)
  # Allow the application to provide values as :snake_symbols, and convert them to the camelStrings
  value = value.reduce({}) { |memo, (k, v)| memo[Member::BuildType.camelize(k.to_s)] = v; memo }

  result = {}

  arguments(ctx).each do |input_key, input_field_defn|
    input_value = value[input_key]
    if value.key?(input_key)
      result[input_key] = if input_value.nil?
        nil
      else
        input_field_defn.type.coerce_result(input_value, ctx)
      end
    end
  end

  result
end

.has_no_arguments(new_has_no_arguments) ⇒ Object

Parameters

  • new_has_no_arguments (Boolean) — Call with true to make this InputObject type ignore the requirement to have any defined arguments.

Returns

  • void

:call-seq:

has_no_arguments(bool new_has_no_arguments) -> void


295
296
297
298
# File 'lib/graphql/schema/input_object.rb', line 295

def has_no_arguments(new_has_no_arguments)
  @has_no_arguments = new_has_no_arguments
  nil
end

.has_no_arguments? ⇒ Boolean

Returns

  • Boolean — true if has_no_arguments(true) was configued

:call-seq:

has_no_arguments?() -> bool

Returns:



306
307
308
# File 'lib/graphql/schema/input_object.rb', line 306

def has_no_arguments?
  @has_no_arguments
end

.kind ⇒ Object



176
177
178
# File 'lib/graphql/schema/input_object.rb', line 176

def kind
  GraphQL::TypeKinds::INPUT_OBJECT
end

.one_of ⇒ Object



145
146
147
148
149
150
151
152
# File 'lib/graphql/schema/input_object.rb', line 145

def one_of
  if !one_of?
    if all_argument_definitions.any? { |arg| arg.type.non_null? }
      raise ArgumentError, "`one_of` may not be used with required arguments -- add `required: false` to argument definitions to use `one_of`"
    end
    directive(GraphQL::Schema::Directive::OneOf)
  end
end

.one_of? ⇒ Boolean

Returns:



154
155
156
# File 'lib/graphql/schema/input_object.rb', line 154

def one_of?
  false # Re-defined when `OneOf` is added
end

.validate_non_null_input(input, ctx, max_errors: nil) ⇒ Object



183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
# File 'lib/graphql/schema/input_object.rb', line 183

def validate_non_null_input(input, ctx, max_errors: nil)
  types = ctx.types

  if input.is_a?(Array)
    return GraphQL::Query::InputValidationResult.from_problem(INVALID_OBJECT_MESSAGE % { object: JSON.generate(input) })
  end

  if !(input.respond_to?(:to_h) || input.respond_to?(:to_unsafe_h))
    # We're not sure it'll act like a hash, so reject it:
    return GraphQL::Query::InputValidationResult.from_problem(INVALID_OBJECT_MESSAGE % { object: JSON.generate(input) })
  end


  result = nil #: GraphQL::Query::InputValidationResult?


  input.each do |argument_name, value|
    argument = types.argument(self, argument_name)
    if argument.nil? && ctx.is_a?(Query::NullContext) && argument_name.is_a?(Symbol)
      # Validating definition directive arguments which come in as Symbols
      argument = types.arguments(self).find { |arg| arg.keyword == argument_name }
    end
    # Items in the input that are unexpected
    if argument.nil?
      result ||= Query::InputValidationResult.new
      result.add_problem("Field is not defined on #{self.graphql_name}", [argument_name])
    else
      # Items in the input that are expected, but have invalid values
      argument_result = argument.type.validate_input(value, ctx)
      if !argument_result.valid?
        result ||= Query::InputValidationResult.new
        result.merge_result!(argument_name, argument_result)
      end
    end
  end

  # Check for missing non-null arguments
  ctx.types.arguments(self).each do |argument|
    if !input.key?(argument.graphql_name) && argument.type.non_null? && !argument.default_value?
      result ||= Query::InputValidationResult.new
      argument_result = argument.type.validate_input(nil, ctx)
      if !argument_result.valid?
        result.merge_result!(argument.graphql_name, argument_result)
      end
    end
  end

  if one_of?
    if input.size == 1
      input.each do |name, value|
        if value.nil?
          result ||= Query::InputValidationResult.new
          result.add_problem("'#{graphql_name}' requires exactly one argument, but '#{name}' was `null`.")
        end
      end
    else
      result ||= Query::InputValidationResult.new
      result.add_problem("'#{graphql_name}' requires exactly one argument, but #{input.size} were provided.")
    end
  end

  result
end

Instance Method Details

#[](key) ⇒ Object

Lookup a key on this object, it accepts new-style underscored symbols Or old-style camelized identifiers.

Parameters

  • key (Symbol, String)

:call-seq:

[](Symbol | String key)


100
101
102
103
104
105
106
107
108
# File 'lib/graphql/schema/input_object.rb', line 100

def [](key)
  if @ruby_style_hash.key?(key)
    @ruby_style_hash[key]
  elsif @arguments
    @arguments[key]
  else
    nil
  end
end

#deconstruct_keys(keys = nil) ⇒ Object



62
63
64
65
66
67
68
69
70
# File 'lib/graphql/schema/input_object.rb', line 62

def deconstruct_keys(keys = nil)
  if keys.nil?
    @ruby_style_hash
  else
    new_h = {}
    keys.each { |k| @ruby_style_hash.key?(k) && new_h[k] = @ruby_style_hash[k] }
    new_h
  end
end

#key?(key) ⇒ Boolean

Returns:



110
111
112
# File 'lib/graphql/schema/input_object.rb', line 110

def key?(key)
  @ruby_style_hash.key?(key) || (@arguments && @arguments.key?(key)) || false
end

#prepare ⇒ Object



72
73
74
# File 'lib/graphql/schema/input_object.rb', line 72

def prepare
  self
end

#to_h ⇒ Object



54
55
56
# File 'lib/graphql/schema/input_object.rb', line 54

def to_h
  unwrap_value(@ruby_style_hash)
end

#to_hash ⇒ Object



58
59
60
# File 'lib/graphql/schema/input_object.rb', line 58

def to_hash
  to_h
end

#to_kwargs ⇒ Object

A copy of the Ruby-style hash



115
116
117
# File 'lib/graphql/schema/input_object.rb', line 115

def to_kwargs
  @ruby_style_hash.dup
end

#unwrap_value(value) ⇒ Object



76
77
78
79
80
81
82
83
84
85
86
87
88
89
# File 'lib/graphql/schema/input_object.rb', line 76

def unwrap_value(value)
  case value
  when Array
    value.map { |item| unwrap_value(item) }
  when Hash
    value.reduce({}) do |h, (key, nested_value)|
      h.merge!(key => unwrap_value(nested_value))
    end
  when InputObject
    value.to_h
  else
    value
  end
end

#validate_for(context) ⇒ Object

:nodoc:



119
120
121
122
123
124
# File 'lib/graphql/schema/input_object.rb', line 119

def validate_for(context) # :nodoc:
  object = context[:current_object]
  # Pass this object's class with `as` so that messages are rendered correctly from inherited validators
  Schema::Validator.validate!(self.class.validators, object, context, @ruby_style_hash, as: self.class)
  nil
end