Class: GraphQL::Schema::Field

Inherits:
Object
  • Object
show all
Extended by:
FindInheritedValue
Includes:
GraphQL::Schema::FindInheritedValue::EmptyObjects, Member::HasArguments, Member::HasAstNode, Member::HasDeprecationReason, Member::HasDirectives, Member::HasPath, Member::HasValidators
Defined in:
lib/graphql/schema/field.rb,
lib/graphql/schema/field/scope_extension.rb,
lib/graphql/schema/field/connection_extension.rb

Defined Under Namespace

Classes: ConnectionExtension, FieldImplementationFailed, MissingReturnTypeError, ScopeExtension

Constant Summary

Constants included from Member::HasDirectives

Member::HasDirectives::NO_DIRECTIVES

Constants included from GraphQL::Schema::FindInheritedValue::EmptyObjects

GraphQL::Schema::FindInheritedValue::EmptyObjects::EMPTY_ARRAY, GraphQL::Schema::FindInheritedValue::EmptyObjects::EMPTY_HASH

Constants included from Member::HasArguments

Member::HasArguments::NO_ARGUMENTS

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Member::HasDeprecationReason

#deprecation_reason, #deprecation_reason=

Methods included from Member::HasDirectives

#directive, #directives, #remove_directive

Methods included from Member::HasValidators

#validates, #validators

Methods included from Member::HasPath

#path

Methods included from Member::HasAstNode

#ast_node

Methods included from Member::HasArguments

#add_argument, #all_argument_definitions, #argument, #argument_class, #arguments, #arguments_statically_coercible?, #coerce_arguments, #get_argument, #own_arguments, #validate_directive_argument

Constructor Details

#initialize(type: nil, name: nil, owner: nil, null: true, field: nil, function: nil, description: nil, deprecation_reason: nil, method: nil, hash_key: nil, dig: nil, resolver_method: nil, resolve: nil, connection: nil, max_page_size: :not_given, scope: nil, introspection: false, camelize: true, trace: nil, complexity: 1, ast_node: nil, extras: EMPTY_ARRAY, extensions: EMPTY_ARRAY, connection_extension: self.class.connection_extension, resolver_class: nil, subscription_scope: nil, relay_node_field: false, relay_nodes_field: false, method_conflict_warning: true, broadcastable: nil, arguments: EMPTY_HASH, directives: EMPTY_HASH, validates: EMPTY_ARRAY, &definition_block) ⇒ Field

Returns a new instance of Field.

Parameters:

  • name (Symbol) (defaults to: nil)

    The underscore-cased version of this field name (will be camelized for the GraphQL API)

  • type (Class, GraphQL::BaseType, Array) (defaults to: nil)

    The return type of this field

  • owner (Class) (defaults to: nil)

    The type that this field belongs to

  • null (Boolean) (defaults to: true)

    true if this field may return null, false if it is never null

  • description (String) (defaults to: nil)

    Field description

  • deprecation_reason (String) (defaults to: nil)

    If present, the field is marked “deprecated” with this message

  • method (Symbol) (defaults to: nil)

    The method to call on the underlying object to resolve this field (defaults to name)

  • hash_key (String, Symbol) (defaults to: nil)

    The hash key to lookup on the underlying object (if its a Hash) to resolve this field (defaults to name or name.to_s)

  • dig (Array<String, Symbol>) (defaults to: nil)

    The nested hash keys to lookup on the underlying hash to resolve this field using dig

  • resolver_method (Symbol) (defaults to: nil)

    The method on the type to call to resolve this field (defaults to name)

  • connection (Boolean) (defaults to: nil)

    true if this field should get automagic connection behavior; default is to infer by *Connection in the return type name

  • connection_extension (Class) (defaults to: self.class.connection_extension)

    The extension to add, to implement connections. If nil, no extension is added.

  • max_page_size (Integer, nil) (defaults to: :not_given)

    For connections, the maximum number of items to return from this field, or nil to allow unlimited results.

  • introspection (Boolean) (defaults to: false)

    If true, this field will be marked as #introspection? and the name may begin with __

  • resolve (<#call(obj, args, ctx)>) (defaults to: nil)

    deprecated for compatibility with <1.8.0

  • field (GraphQL::Field, GraphQL::Schema::Field) (defaults to: nil)

    deprecated for compatibility with <1.8.0

  • function (GraphQL::Function) (defaults to: nil)

    deprecated for compatibility with <1.8.0

  • resolver_class (Class) (defaults to: nil)

    (Private) A Resolver which this field was derived from. Use resolver: to create a field with a resolver.

  • arguments ({String=>GraphQL::Schema::Argument, Hash}) (defaults to: EMPTY_HASH)

    Arguments for this field (may be added in the block, also)

  • camelize (Boolean) (defaults to: true)

    If true, the field name will be camelized when building the schema

  • complexity (Numeric) (defaults to: 1)

    When provided, set the complexity for this field

  • scope (Boolean) (defaults to: nil)

    If true, the return type’s .scope_items method will be called on the return value

  • subscription_scope (Symbol, String) (defaults to: nil)

    A key in context which will be used to scope subscription payloads

  • extensions (Array<Class, Hash<Class => Object>>) (defaults to: EMPTY_ARRAY)

    Named extensions to apply to this field (see also #extension)

  • directives (Hash{Class => Hash}) (defaults to: EMPTY_HASH)

    Directives to apply to this field

  • trace (Boolean) (defaults to: nil)

    If true, a Tracing tracer will measure this scalar field

  • broadcastable (Boolean) (defaults to: nil)

    Whether or not this field can be distributed in subscription broadcasts

  • ast_node (Language::Nodes::FieldDefinition, nil) (defaults to: nil)

    If this schema was parsed from definition, this AST node defined the field

  • method_conflict_warning (Boolean) (defaults to: true)

    If false, skip the warning if this field’s method conflicts with a built-in method

  • validates (Array<Hash>) (defaults to: EMPTY_ARRAY)

    Configurations for validating this field



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
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
# File 'lib/graphql/schema/field.rb', line 200

def initialize(type: nil, name: nil, owner: nil, null: true, field: nil, function: nil, description: nil, deprecation_reason: nil, method: nil, hash_key: nil, dig: nil, resolver_method: nil, resolve: nil, connection: nil, max_page_size: :not_given, scope: nil, introspection: false, camelize: true, trace: nil, complexity: 1, ast_node: nil, extras: EMPTY_ARRAY, extensions: EMPTY_ARRAY, connection_extension: self.class.connection_extension, resolver_class: nil, subscription_scope: nil, relay_node_field: false, relay_nodes_field: false, method_conflict_warning: true, broadcastable: nil, arguments: EMPTY_HASH, directives: EMPTY_HASH, validates: EMPTY_ARRAY, &definition_block)
  if name.nil?
    raise ArgumentError, "missing first `name` argument or keyword `name:`"
  end
  if !(field || function || resolver_class)
    if type.nil?
      raise ArgumentError, "missing second `type` argument or keyword `type:`"
    end
  end
  if (field || function || resolve) && extras.any?
    raise ArgumentError, "keyword `extras:` may only be used with method-based resolve and class-based field such as mutation class, please remove `field:`, `function:` or `resolve:`"
  end
  @original_name = name
  name_s = -name.to_s
  @underscored_name = -Member::BuildType.underscore(name_s)
  @name = -(camelize ? Member::BuildType.camelize(name_s) : name_s)
  @description = description
  if field.is_a?(GraphQL::Schema::Field)
    raise ArgumentError, "Instead of passing a field as `field:`, use `add_field(field)` to add an already-defined field."
  else
    @field = field
  end
  @function = function
  @resolve = resolve
  self.deprecation_reason = deprecation_reason

  if method && hash_key && dig
    raise ArgumentError, "Provide `method:`, `hash_key:` _or_ `dig:`, not multiple. (called with: `method: #{method.inspect}, hash_key: #{hash_key.inspect}, dig: #{dig.inspect}`)"
  end

  if resolver_method
    if method
      raise ArgumentError, "Provide `method:` _or_ `resolver_method:`, not both. (called with: `method: #{method.inspect}, resolver_method: #{resolver_method.inspect}`)"
    end

    if hash_key || dig
      raise ArgumentError, "Provide `hash_key:`, `dig:`, _or_ `resolver_method:`, not multiple. (called with: `hash_key: #{hash_key.inspect}, dig: #{dig.inspect}, resolver_method: #{resolver_method.inspect}`)"
    end
  end

  # TODO: I think non-string/symbol hash keys are wrongly normalized (eg `1` will not work)
  method_name = method || hash_key || name_s
  @dig_keys = dig
  resolver_method ||= name_s.to_sym

  @method_str = -method_name.to_s
  @method_sym = method_name.to_sym
  @resolver_method = resolver_method
  @complexity = complexity
  @return_type_expr = type
  @return_type_null = null
  @connection = connection
  @has_max_page_size = max_page_size != :not_given
  @max_page_size = max_page_size == :not_given ? nil : max_page_size
  @introspection = introspection
  @extras = extras
  @broadcastable = broadcastable
  @resolver_class = resolver_class
  @scope = scope
  @trace = trace
  @relay_node_field = relay_node_field
  @relay_nodes_field = relay_nodes_field
  @ast_node = ast_node
  @method_conflict_warning = method_conflict_warning

  arguments.each do |name, arg|
    case arg
    when Hash
      argument(name: name, **arg)
    when GraphQL::Schema::Argument
      add_argument(arg)
    when Array
      arg.each { |a| add_argument(a) }
    else
      raise ArgumentError, "Unexpected argument config (#{arg.class}): #{arg.inspect}"
    end
  end

  @owner = owner
  @subscription_scope = subscription_scope

  @extensions = EMPTY_ARRAY
  @call_after_define = false
  # This should run before connection extension,
  # but should it run after the definition block?
  if scoped?
    self.extension(ScopeExtension)
  end

  # The problem with putting this after the definition_block
  # is that it would override arguments
  if connection? && connection_extension
    self.extension(connection_extension)
  end

  # Do this last so we have as much context as possible when initializing them:
  if extensions.any?
    self.extensions(extensions)
  end

  if directives.any?
    directives.each do |(dir_class, options)|
      self.directive(dir_class, **options)
    end
  end

  self.validates(validates)

  if definition_block
    if definition_block.arity == 1
      yield self
    else
      instance_eval(&definition_block)
    end
  end

  self.extensions.each(&:after_define_apply)
  @call_after_define = true
end

Instance Attribute Details

#description(text = nil) ⇒ String

Parameters:

  • text (String) (defaults to: nil)

Returns:

  • (String)


329
330
331
332
333
334
335
# File 'lib/graphql/schema/field.rb', line 329

def description(text = nil)
  if text
    @description = text
  else
    @description
  end
end

#max_page_sizeInteger? (readonly)

Returns Applied to connections if #has_max_page_size?.

Returns:



492
493
494
# File 'lib/graphql/schema/field.rb', line 492

def max_page_size
  @max_page_size
end

#method_strString (readonly)

Returns Method or hash key on the underlying object to look up.

Returns:

  • (String)

    Method or hash key on the underlying object to look up



29
30
31
# File 'lib/graphql/schema/field.rb', line 29

def method_str
  @method_str
end

#method_symSymbol (readonly)

Returns Method or hash key on the underlying object to look up.

Returns:

  • (Symbol)

    Method or hash key on the underlying object to look up



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

def method_sym
  @method_sym
end

#nameString (readonly) Also known as: graphql_name

Returns the GraphQL name for this field, camelized unless camelize: false is provided.

Returns:

  • (String)

    the GraphQL name for this field, camelized unless camelize: false is provided



20
21
22
# File 'lib/graphql/schema/field.rb', line 20

def name
  @name
end

#original_nameSymbol (readonly)

Returns the original name of the field, passed in by the user.

Returns:

  • (Symbol)

    the original name of the field, passed in by the user



49
50
51
# File 'lib/graphql/schema/field.rb', line 49

def original_name
  @original_name
end

#ownerClass

Returns The thing this field was defined on (type, mutation, resolver).

Returns:

  • (Class)

    The thing this field was defined on (type, mutation, resolver)



35
36
37
# File 'lib/graphql/schema/field.rb', line 35

def owner
  @owner
end

#relay_node_fieldObject (readonly)

Returns Boolean.

Returns:

  • Boolean



163
164
165
# File 'lib/graphql/schema/field.rb', line 163

def relay_node_field
  @relay_node_field
end

#resolver_methodSymbol (readonly)

Returns The method on the type to look up.

Returns:

  • (Symbol)

    The method on the type to look up



32
33
34
# File 'lib/graphql/schema/field.rb', line 32

def resolver_method
  @resolver_method
end

#subscription_scopeString?

Returns:

  • (String, nil)


71
72
73
# File 'lib/graphql/schema/field.rb', line 71

def subscription_scope
  @subscription_scope
end

#traceBoolean (readonly)

Returns Apply tracing to this field? (Default: skip scalars, this is the override value).

Returns:

  • (Boolean)

    Apply tracing to this field? (Default: skip scalars, this is the override value)



68
69
70
# File 'lib/graphql/schema/field.rb', line 68

def trace
  @trace
end

#typeObject



497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
# File 'lib/graphql/schema/field.rb', line 497

def type
  @type ||= if @function
    Member::BuildType.parse_type(@function.type, null: false)
  elsif @field
    Member::BuildType.parse_type(@field.type, null: false)
  elsif @return_type_expr.nil?
    # Not enough info to determine type
    message = "Can't determine the return type for #{self.path}"
    if @resolver_class
      message += " (it has `resolver: #{@resolver_class}`, consider configuration a `type ...` for that class)"
    end
    raise MissingReturnTypeError, message
  else
    Member::BuildType.parse_type(@return_type_expr, null: @return_type_null)
  end
rescue GraphQL::Schema::InvalidDocumentError, MissingReturnTypeError => err
  # Let this propagate up
  raise err
rescue StandardError => err
  raise MissingReturnTypeError, "Failed to build return type for #{@owner.graphql_name}.#{name} from #{@return_type_expr.inspect}: (#{err.class}) #{err.message}", err.backtrace
end

Class Method Details

.connection_extension(new_extension_class = nil) ⇒ Class

This extension is applied to fields when #connection? is true.

You can override it in your base field definition.

Examples:

Configuring a custom extension

class Types::BaseField < GraphQL::Schema::Field
  connection_extension(MyCustomExtension)
end

Returns:



154
155
156
157
158
159
160
# File 'lib/graphql/schema/field.rb', line 154

def self.connection_extension(new_extension_class = nil)
  if new_extension_class
    @connection_extension = new_extension_class
  else
    @connection_extension ||= find_inherited_value(:connection_extension, ConnectionExtension)
  end
end

.from_options(name = nil, type = nil, desc = nil, resolver: nil, mutation: nil, subscription: nil, **kwargs, &block) ⇒ GraphQL::Schema:Field

Create a field instance from a list of arguments, keyword arguments, and a block.

This method implements prioritization between the resolver or mutation defaults and the local overrides via other keywords.

It also normalizes positional arguments into keywords for #initialize.

Parameters:

  • resolver (Class) (defaults to: nil)

    A Resolver class to use for field configuration

  • mutation (Class) (defaults to: nil)

    A Mutation class to use for field configuration

  • subscription (Class) (defaults to: nil)

    A Subscription class to use for field configuration

Returns:

  • (GraphQL::Schema:Field)

    an instance of `self

See Also:

  • for other options


84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
# File 'lib/graphql/schema/field.rb', line 84

def self.from_options(name = nil, type = nil, desc = nil, resolver: nil, mutation: nil, subscription: nil,**kwargs, &block)
  if (parent_config = resolver || mutation || subscription)
    # Get the parent config, merge in local overrides
    kwargs = parent_config.field_options.merge(kwargs)
    # Add a reference to that parent class
    kwargs[:resolver_class] = parent_config
  end

  if name
    kwargs[:name] = name
  end

  if !type.nil?
    if desc
      if kwargs[:description]
        raise ArgumentError, "Provide description as a positional argument or `description:` keyword, but not both (#{desc.inspect}, #{kwargs[:description].inspect})"
      end

      kwargs[:description] = desc
      kwargs[:type] = type
    elsif (kwargs[:field] || kwargs[:function] || resolver || mutation) && type.is_a?(String)
      # The return type should be copied from `field` or `function`, and the second positional argument is the description
      kwargs[:description] = type
    else
      kwargs[:type] = type
    end
    if type.is_a?(Class) && type < GraphQL::Schema::Mutation
      raise ArgumentError, "Use `field #{name.inspect}, mutation: Mutation, ...` to provide a mutation to this field instead"
    end
  end
  new(**kwargs, &block)
end

Instance Method Details

#accessible?(context) ⇒ Boolean

Returns:

  • (Boolean)


527
528
529
530
531
532
533
# File 'lib/graphql/schema/field.rb', line 527

def accessible?(context)
  if @resolver_class
    @resolver_class.accessible?(context)
  else
    true
  end
end

#authorized?(object, args, context) ⇒ Boolean

Returns:

  • (Boolean)


535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
# File 'lib/graphql/schema/field.rb', line 535

def authorized?(object, args, context)
  if @resolver_class
    # The resolver _instance_ will check itself during `resolve()`
    @resolver_class.authorized?(object, context)
  else
    if (arg_values = context[:current_arguments])
      # ^^ that's provided by the interpreter at runtime, and includes info about whether the default value was used or not.
      using_arg_values = true
      arg_values = arg_values.argument_values
    else
      arg_values = args
      using_arg_values = false
    end
    # Faster than `.any?`
    arguments(context).each_value do |arg|
      arg_key = arg.keyword
      if arg_values.key?(arg_key)
        arg_value = arg_values[arg_key]
        if using_arg_values
          if arg_value.default_used?
            # pass -- no auth required for default used
            next
          else
            application_arg_value = arg_value.value
            if application_arg_value.is_a?(GraphQL::Execution::Interpreter::Arguments)
              application_arg_value.keyword_arguments
            end
          end
        else
          application_arg_value = arg_value
        end

        if !arg.authorized?(object, application_arg_value, context)
          return false
        end
      end
    end
    true
  end
end

#broadcastable?Boolean?

If true, subscription updates with this field can be shared between viewers

Returns:

  • (Boolean, nil)

See Also:



323
324
325
# File 'lib/graphql/schema/field.rb', line 323

def broadcastable?
  @broadcastable
end

#calculate_complexity(query:, nodes:, child_complexity:) ⇒ Object



407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
# File 'lib/graphql/schema/field.rb', line 407

def calculate_complexity(query:, nodes:, child_complexity:)
  if respond_to?(:complexity_for)
    lookahead = GraphQL::Execution::Lookahead.new(query: query, field: self, ast_nodes: nodes, owner_type: owner)
    complexity_for(child_complexity: child_complexity, query: query, lookahead: lookahead)
  elsif connection?
    arguments = query.arguments_for(nodes.first, self)
    max_possible_page_size = nil
    if arguments.respond_to?(:[]) # It might have been an error
      if arguments[:first]
        max_possible_page_size = arguments[:first]
      end

      if arguments[:last] && (max_possible_page_size.nil? || arguments[:last] > max_possible_page_size)
        max_possible_page_size = arguments[:last]
      end
    end

    if max_possible_page_size.nil?
      max_possible_page_size = max_page_size || query.schema.default_max_page_size
    end

    if max_possible_page_size.nil?
      raise GraphQL::Error, "Can't calculate complexity for #{path}, no `first:`, `last:`, `max_page_size` or `default_max_page_size`"
    else
       = 0
      lookahead = GraphQL::Execution::Lookahead.new(query: query, field: self, ast_nodes: nodes, owner_type: owner)

      if (page_info_lookahead = lookahead.selection(:page_info)).selected?
         += 1 # pageInfo
         += page_info_lookahead.selections.size # subfields
      end

      if lookahead.selects?(:total) || lookahead.selects?(:total_count) || lookahead.selects?(:count)
         += 1
      end

      nodes_edges_complexity = 0
      nodes_edges_complexity += 1 if lookahead.selects?(:edges)
      nodes_edges_complexity += 1 if lookahead.selects?(:nodes)

      # Possible bug: selections on `edges` and `nodes` are _both_ multiplied here. Should they be?
      items_complexity = child_complexity -  - nodes_edges_complexity
      # Add 1 for _this_ field
      1 + (max_possible_page_size * items_complexity) +  + nodes_edges_complexity
    end
  else
    defined_complexity = complexity
    case defined_complexity
    when Proc
      arguments = query.arguments_for(nodes.first, self)
      defined_complexity.call(query.context, arguments.keyword_arguments, child_complexity)
    when Numeric
      defined_complexity + child_complexity
    else
      raise("Invalid complexity: #{defined_complexity.inspect} on #{path} (#{inspect})")
    end
  end
end

#complexity(new_complexity = nil) ⇒ Object



466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
# File 'lib/graphql/schema/field.rb', line 466

def complexity(new_complexity = nil)
  case new_complexity
  when Proc
    if new_complexity.parameters.size != 3
      fail(
        "A complexity proc should always accept 3 parameters: ctx, args, child_complexity. "\
        "E.g.: complexity ->(ctx, args, child_complexity) { child_complexity * args[:limit] }"
      )
    else
      @complexity = new_complexity
    end
  when Numeric
    @complexity = new_complexity
  when nil
    @complexity
  else
    raise("Invalid complexity: #{new_complexity.inspect} on #{@name}")
  end
end

#connection?Boolean

Can be set with connection: true|false or inferred from a type name ending in *Connection

Returns:

  • (Boolean)

    if true, this field will be wrapped with Relay connection behavior



119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
# File 'lib/graphql/schema/field.rb', line 119

def connection?
  if @connection.nil?
    # Provide default based on type name
    return_type_name = if (contains_type = @field || @function)
      Member::BuildType.to_type_name(contains_type.type)
    elsif @return_type_expr
      Member::BuildType.to_type_name(@return_type_expr)
    else
      # As a last ditch, try to force loading the return type:
      type.unwrap.name
    end
    @connection = return_type_name.end_with?("Connection")
  else
    @connection
  end
end

#extension(extension_class, options = nil) ⇒ void

This method returns an undefined value.

Add extension to this field, initialized with options if provided.

Examples:

adding an extension

extension(MyExtensionClass)

adding an extension with options

extension(MyExtensionClass, filter: true)

Parameters:

  • extension_class (Class)
  • options (Hash) (defaults to: nil)

    if provided, given as options: when initializing extension.



377
378
379
380
381
382
383
384
385
386
387
# File 'lib/graphql/schema/field.rb', line 377

def extension(extension_class, options = nil)
  extension_inst = extension_class.new(field: self, options: options)
  if @extensions.frozen?
    @extensions = @extensions.dup
  end
  if @call_after_define
    extension_inst.after_define_apply
  end
  @extensions << extension_inst
  nil
end

#extensions(new_extensions = nil) ⇒ Array<GraphQL::Schema::FieldExtension>

Read extension instances from this field, or add new classes/options to be initialized on this field. Extensions are executed in the order they are added.

Examples:

adding an extension

extensions([MyExtensionClass])

adding multiple extensions

extensions([MyExtensionClass, AnotherExtensionClass])

adding an extension with options

extensions([MyExtensionClass, { AnotherExtensionClass => { filter: true } }])

Parameters:

  • extensions (Array<Class, Hash<Class => Hash>>)

    Add extensions to this field. For hash elements, only the first key/value is used.

Returns:



352
353
354
355
356
357
358
359
360
361
362
363
364
# File 'lib/graphql/schema/field.rb', line 352

def extensions(new_extensions = nil)
  if new_extensions
    new_extensions.each do |extension_config|
      if extension_config.is_a?(Hash)
        extension_class, options = *extension_config.to_a[0]
        self.extension(extension_class, options)
      else
        self.extension(extension_config)
      end
    end
  end
  @extensions
end

#extras(new_extras = nil) ⇒ Array<Symbol>

Read extras (as symbols) from this field, or add new extras to be opted into by this field’s resolver.

Parameters:

  • new_extras (Array<Symbol>) (defaults to: nil)

    Add extras to this field

Returns:

  • (Array<Symbol>)


394
395
396
397
398
399
400
401
402
403
404
405
# File 'lib/graphql/schema/field.rb', line 394

def extras(new_extras = nil)
  if new_extras.nil?
    # Read the value
    @extras
  else
    if @extras.frozen?
      @extras = @extras.dup
    end
    # Append to the set of extras on this field
    @extras.concat(new_extras)
  end
end

#fetch_extra(extra_name, ctx) ⇒ Object

Parameters:



609
610
611
612
613
614
615
616
617
# File 'lib/graphql/schema/field.rb', line 609

def fetch_extra(extra_name, ctx)
  if extra_name != :path && extra_name != :ast_node && respond_to?(extra_name)
    self.public_send(extra_name)
  elsif ctx.respond_to?(extra_name)
    ctx.public_send(extra_name)
  else
    raise GraphQL::RequiredImplementationMissingError, "Unknown field extra for #{self.path}: #{extra_name.inspect}"
  end
end

#has_max_page_size?Boolean

Returns True if this field’s #max_page_size should override the schema default.

Returns:

  • (Boolean)

    True if this field’s #max_page_size should override the schema default.



487
488
489
# File 'lib/graphql/schema/field.rb', line 487

def has_max_page_size?
  @has_max_page_size
end

#inspectObject



61
62
63
# File 'lib/graphql/schema/field.rb', line 61

def inspect
  "#<#{self.class} #{path}#{all_argument_definitions.any? ? "(...)" : ""}: #{type.to_type_signature}>"
end

#introspection?Boolean

Returns Is this field a predefined introspection field?.

Returns:

  • (Boolean)

    Is this field a predefined introspection field?



57
58
59
# File 'lib/graphql/schema/field.rb', line 57

def introspection?
  @introspection
end

#method_conflict_warning?Boolean

Returns Should we warn if this field’s name conflicts with a built-in method?.

Returns:

  • (Boolean)

    Should we warn if this field’s name conflicts with a built-in method?



166
167
168
# File 'lib/graphql/schema/field.rb', line 166

def method_conflict_warning?
  @method_conflict_warning
end

#owner_typeClass

Returns The GraphQL type this field belongs to. (For fields defined on mutations, it’s the payload type).

Returns:

  • (Class)

    The GraphQL type this field belongs to. (For fields defined on mutations, it’s the payload type)



38
39
40
41
42
43
44
45
46
# File 'lib/graphql/schema/field.rb', line 38

def owner_type
  @owner_type ||= if owner.nil?
    raise GraphQL::InvariantError, "Field #{original_name.inspect} (graphql name: #{graphql_name.inspect}) has no owner, but all fields should have an owner. How did this happen?!"
  elsif owner < GraphQL::Schema::Mutation
    owner.payload_type
  else
    owner
  end
end

#resolve(object, args, ctx) ⇒ Object

This method is called by the interpreter for each field. You can extend it in your base field classes.

Parameters:



581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
# File 'lib/graphql/schema/field.rb', line 581

def resolve(object, args, ctx)
  if @resolve_proc
    raise "Can't run resolve proc for #{path} when using GraphQL::Execution::Interpreter"
  end
  begin
    # Unwrap the GraphQL object to get the application object.
    application_object = object.object

    Schema::Validator.validate!(validators, application_object, ctx, args)

    ctx.schema.after_lazy(self.authorized?(application_object, args, ctx)) do |is_authorized|
      if is_authorized
        public_send_field(object, args, ctx)
      else
        raise GraphQL::UnauthorizedFieldError.new(object: application_object, type: object.class, context: ctx, field: self)
      end
    end
  rescue GraphQL::UnauthorizedFieldError => err
    err.field ||= self
    ctx.schema.unauthorized_field(err)
  rescue GraphQL::UnauthorizedError => err
    ctx.schema.unauthorized_object(err)
  end
rescue GraphQL::ExecutionError => err
  err
end

#resolverClass? Also known as: mutation

Returns The Resolver this field was derived from, if there is one.

Returns:

  • (Class, nil)

    The Resolver this field was derived from, if there is one



52
53
54
# File 'lib/graphql/schema/field.rb', line 52

def resolver
  @resolver_class
end

#scoped?Boolean

Returns if true, the return type’s .scope_items method will be applied to this field’s return value.

Returns:

  • (Boolean)

    if true, the return type’s .scope_items method will be applied to this field’s return value



137
138
139
140
141
142
143
144
# File 'lib/graphql/schema/field.rb', line 137

def scoped?
  if !@scope.nil?
    # The default was overridden
    @scope
  else
    @return_type_expr && (@return_type_expr.is_a?(Array) || (@return_type_expr.is_a?(String) && @return_type_expr.include?("[")) || connection?)
  end
end

#visible?(context) ⇒ Boolean

Returns:

  • (Boolean)


519
520
521
522
523
524
525
# File 'lib/graphql/schema/field.rb', line 519

def visible?(context)
  if @resolver_class
    @resolver_class.visible?(context)
  else
    true
  end
end