Class: GraphQL::Schema::Field

Inherits:
Object
  • Object
show all
Extended by:
FindInheritedValue
Includes:
EmptyObjects, Member::HasArguments, Member::HasArguments::FieldConfigured, 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, ExtendedState, FieldImplementationFailed, MissingReturnTypeError, ScopeExtension

Constant Summary

Constants included from EmptyObjects

EmptyObjects::EMPTY_ARRAY, EmptyObjects::EMPTY_HASH

Constants included from Member::HasArguments

Member::HasArguments::NO_ARGUMENTS

Instance Attribute Summary collapse

Attributes included from Member::HasDeprecationReason

#deprecation_reason

Attributes included from Member::HasAstNode

#ast_node

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Member::HasDirectives

add_directive, #directive, get_directives, #inherited, #remove_directive, remove_directive

Methods included from Member::HasValidators

#validates, #validators

Methods included from Member::HasPath

#path

Methods included from Member::HasAstNode

#inherited

Methods included from Member::HasArguments::FieldConfigured

#all_argument_definitions, #any_arguments?, #arguments

Methods included from Member::HasArguments

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

Constructor Details

#initialize(type: nil, name: nil, owner: nil, null: nil, description: NOT_CONFIGURED, comment: NOT_CONFIGURED, deprecation_reason: nil, method: nil, hash_key: nil, dig: nil, resolver_method: nil, connection: nil, max_page_size: NOT_CONFIGURED, default_page_size: NOT_CONFIGURED, scope: nil, introspection: false, camelize: true, trace: nil, complexity: nil, 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: NOT_CONFIGURED, arguments: EMPTY_HASH, directives: EMPTY_HASH, validates: EMPTY_ARRAY, fallback_value: NOT_CONFIGURED, dynamic_introspection: false, &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: nil)

    (defaults to true) true if this field may return null, false if it is never null

  • description (String) (defaults to: NOT_CONFIGURED)

    Field description

  • comment (String) (defaults to: NOT_CONFIGURED)

    Field comment

  • 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_CONFIGURED)

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

  • default_page_size (Integer, nil) (defaults to: NOT_CONFIGURED)

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

  • introspection (Boolean) (defaults to: false)

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

  • 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: nil)

    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: NOT_CONFIGURED)

    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

  • fallback_value (Object) (defaults to: NOT_CONFIGURED)

    A fallback value if the method is not defined



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
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
# File 'lib/graphql/schema/field.rb', line 244

def initialize(type: nil, name: nil, owner: nil, null: nil, description: NOT_CONFIGURED, comment: NOT_CONFIGURED, deprecation_reason: nil, method: nil, hash_key: nil, dig: nil, resolver_method: nil, connection: nil, max_page_size: NOT_CONFIGURED, default_page_size: NOT_CONFIGURED, scope: nil, introspection: false, camelize: true, trace: nil, complexity: nil, 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: NOT_CONFIGURED, arguments: EMPTY_HASH, directives: EMPTY_HASH, validates: EMPTY_ARRAY, fallback_value: NOT_CONFIGURED, dynamic_introspection: false, &definition_block)
  if name.nil?
    raise ArgumentError, "missing first `name` argument or keyword `name:`"
  end
  if !(resolver_class)
    if type.nil? && !block_given?
      raise ArgumentError, "missing second `type` argument, keyword `type:`, or a block containing `type(...)`"
    end
  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
  @comment = comment
  @type = @owner_type = @own_validators = @own_directives = @own_arguments = @arguments_statically_coercible = nil # these will be prepared later if necessary

  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

  method_name = method || hash_key || name_s
  @dig_keys = dig
  if hash_key
    @hash_key = hash_key
    @hash_key_str = hash_key.to_s
  else
    @hash_key = NOT_CONFIGURED
    @hash_key_str = NOT_CONFIGURED
  end

  @method_str = -method_name.to_s
  @method_sym = method_name.to_sym
  @resolver_method = (resolver_method || name_s).to_sym
  @complexity = complexity
  @dynamic_introspection = dynamic_introspection
  @return_type_expr = type
  @return_type_null = if !null.nil?
    null
  elsif resolver_class
    nil
  else
    true
  end
  @connection = connection
  @max_page_size = max_page_size
  @default_page_size = default_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
  @fallback_value = fallback_value
  @definition_block = definition_block

  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
  set_pagination_extensions(connection_extension: connection_extension)
  # Do this last so we have as much context as possible when initializing them:
  if !extensions.empty?
    self.extensions(extensions)
  end

  if resolver_class && !resolver_class.extensions.empty?
    self.extensions(resolver_class.extensions)
  end

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

  if !validates.empty?
    self.validates(validates)
  end

  if @definition_block.nil?
    self.extensions.each(&:after_define_apply)
    @call_after_define = true
  end
end

Instance Attribute Details

#description(text = nil) ⇒ String

Parameters:

  • text (String) (defaults to: nil)

Returns:

  • (String)


398
399
400
401
402
403
404
405
406
407
408
# File 'lib/graphql/schema/field.rb', line 398

def description(text = nil)
  if text
    @description = text
  elsif !NOT_CONFIGURED.equal?(@description)
    @description
  elsif @resolver_class
    @resolver_class.description
  else
    nil
  end
end

#dig_keysObject (readonly)

Returns the value of attribute dig_keys.



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

def dig_keys
  @dig_keys
end

#dynamic_introspectionObject

Returns the value of attribute dynamic_introspection.



381
382
383
# File 'lib/graphql/schema/field.rb', line 381

def dynamic_introspection
  @dynamic_introspection
end

#hash_keyObject (readonly)

Returns the value of attribute hash_key.



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

def hash_key
  @hash_key
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



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

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



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

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



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

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



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

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)



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

def owner
  @owner
end

#relay_node_fieldObject (readonly)

Returns Boolean.

Returns:

  • Boolean



205
206
207
# File 'lib/graphql/schema/field.rb', line 205

def relay_node_field
  @relay_node_field
end

#relay_nodes_fieldObject (readonly)

Returns Boolean.

Returns:

  • Boolean



207
208
209
# File 'lib/graphql/schema/field.rb', line 207

def relay_nodes_field
  @relay_nodes_field
end

#subscription_scopeString?

Returns:

  • (String, nil)


93
94
95
# File 'lib/graphql/schema/field.rb', line 93

def subscription_scope
  @subscription_scope || (@resolver_class.respond_to?(:subscription_scope) ? @resolver_class.subscription_scope : nil)
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)



90
91
92
# File 'lib/graphql/schema/field.rb', line 90

def trace
  @trace
end

#type(new_type = NOT_CONFIGURED) ⇒ Module, ...

Get or set the return type of this field.

It may return nil if no type was configured or if the given definition block wasn’t called yet.

Parameters:

Returns:



613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
# File 'lib/graphql/schema/field.rb', line 613

def type(new_type = NOT_CONFIGURED)
  if NOT_CONFIGURED.equal?(new_type)
    if @resolver_class
      return_type = @return_type_expr || @resolver_class.type_expr
      if return_type.nil?
        raise MissingReturnTypeError, "Can't determine the return type for #{self.path} (it has `resolver: #{@resolver_class}`, perhaps that class is missing a `type ...` declaration, or perhaps its type causes a cyclical loading issue)"
      end
      nullable = @return_type_null.nil? ? @resolver_class.null : @return_type_null
      Member::BuildType.parse_type(return_type, null: nullable)
    elsif !@return_type_expr.nil?
      @type ||= Member::BuildType.parse_type(@return_type_expr, null: @return_type_null)
    end
  else
    @return_type_expr = new_type
    # If `type` is set in the definition block, then the `connection_extension: ...` given as a keyword won't be used, hmm...
    # Also, arguments added by `connection_extension` will clobber anything previously defined,
    # so `type(...)` should go first.
    set_pagination_extensions(connection_extension: self.class.connection_extension)
  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:



196
197
198
199
200
201
202
# File 'lib/graphql/schema/field.rb', line 196

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, comment: 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


109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
# File 'lib/graphql/schema/field.rb', line 109

def self.from_options(name = nil, type = nil, desc = nil, comment: nil, resolver: nil, mutation: nil, subscription: nil,**kwargs, &block)
  if (resolver_class = resolver || mutation || subscription)
    # Add a reference to that parent class
    kwargs[:resolver_class] = resolver_class
  end

  if name
    kwargs[:name] = name
  end

  if comment
    kwargs[:comment] = comment
  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 (resolver || mutation) && type.is_a?(String)
      # The return type should be copied from the resolver, 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

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

Returns:

  • (Boolean)


647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
# File 'lib/graphql/schema/field.rb', line 647

def authorized?(object, args, context)
  if @resolver_class
    # The resolver _instance_ will check itself during `resolve()`
    @resolver_class.authorized?(object, context)
  else
    if args.size > 0
      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

      args = context.types.arguments(self)
      args.each 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
    end
    true
  end
end

#broadcastable?Boolean?

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

Returns:

  • (Boolean, nil)

See Also:



386
387
388
389
390
391
392
393
394
# File 'lib/graphql/schema/field.rb', line 386

def broadcastable?
  if !NOT_CONFIGURED.equal?(@broadcastable)
    @broadcastable
  elsif @resolver_class
    @resolver_class.broadcastable?
  else
    nil
  end
end

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



499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
# File 'lib/graphql/schema/field.rb', line 499

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
    elsif arguments.is_a?(GraphQL::ExecutionError) || arguments.is_a?(GraphQL::UnauthorizedError)
      raise arguments
    end

    if max_possible_page_size.nil?
      max_possible_page_size = default_page_size || query.schema.default_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:`, `default_page_size`, `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)

      lookahead.selections.each do |next_lookahead|
        # this includes `pageInfo`, `nodes` and `edges` and any custom fields
        # TODO this doesn't support procs yet -- unlikely to need it.
         += next_lookahead.field.complexity
        if next_lookahead.name != :nodes && next_lookahead.name != :edges
          # subfields, eg, for pageInfo -- assumes no subselections
           += next_lookahead.selections.size
        end
      end

      # Possible bug: selections on `edges` and `nodes` are _both_ multiplied here. Should they be?
      items_complexity = child_complexity - 
      subfields_complexity = (max_possible_page_size * items_complexity) + 
      # Apply this field's own complexity
      apply_own_complexity_to(subfields_complexity, query, nodes)
    end
  else
    apply_own_complexity_to(child_complexity, query, nodes)
  end
end

#comment(text = nil) ⇒ String?

Parameters:

  • text (String) (defaults to: nil)

Returns:

  • (String, nil)


412
413
414
415
416
417
418
419
420
421
422
# File 'lib/graphql/schema/field.rb', line 412

def comment(text = nil)
  if text
    @comment = text
  elsif !NOT_CONFIGURED.equal?(@comment)
    @comment
  elsif @resolver_class
    @resolver_class.comment
  else
    nil
  end
end

#complexity(new_complexity = nil) ⇒ Object



549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
# File 'lib/graphql/schema/field.rb', line 549

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
    if @resolver_class
      @complexity || @resolver_class.complexity || 1
    else
      @complexity || 1
    end
  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



146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
# File 'lib/graphql/schema/field.rb', line 146

def connection?
  if @connection.nil?
    # Provide default based on type name
    return_type_name = if @return_type_expr
      Member::BuildType.to_type_name(@return_type_expr)
    elsif @resolver_class && @resolver_class.type
      Member::BuildType.to_type_name(@resolver_class.type)
    elsif type
      # As a last ditch, try to force loading the return type:
      type.unwrap.name
    end
    if return_type_name
      @connection = return_type_name.end_with?("Connection") && return_type_name != "Connection"
    else
      # TODO set this when type is set by method
      false # not loaded yet?
    end
  else
    @connection
  end
end

#default_page_sizeInteger?

Returns Applied to connections if #has_default_page_size?.

Returns:



595
596
597
598
599
600
601
602
603
# File 'lib/graphql/schema/field.rb', line 595

def default_page_size
  if !NOT_CONFIGURED.equal?(@default_page_size)
    @default_page_size
  elsif @resolver_class && @resolver_class.has_default_page_size?
    @resolver_class.default_page_size
  else
    nil
  end
end

#directivesObject



44
45
46
47
48
49
50
51
52
53
54
# File 'lib/graphql/schema/field.rb', line 44

def directives
  if @resolver_class && !(r_dirs = @resolver_class.directives).empty?
    if !(own_dirs = super).empty?
      own_dirs + r_dirs
    else
      r_dirs
    end
  else
    super
  end
end

#ensure_loadedself

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Calls the definition block, if one was given. This is deferred so that references to the return type can be lazily evaluated, reducing Rails boot time.

Returns:

  • (self)


367
368
369
370
371
372
373
374
375
376
377
378
379
# File 'lib/graphql/schema/field.rb', line 367

def ensure_loaded
  if @definition_block
    if @definition_block.arity == 1
      @definition_block.call(self)
    else
      instance_eval(&@definition_block)
    end
    self.extensions.each(&:after_define_apply)
    @call_after_define = true
    @definition_block = nil
  end
  self
end

#extension(extension_class, **options) ⇒ 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:



464
465
466
467
468
469
470
471
472
473
474
# File 'lib/graphql/schema/field.rb', line 464

def extension(extension_class, **options)
  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:



439
440
441
442
443
444
445
446
447
448
449
450
451
# File 'lib/graphql/schema/field.rb', line 439

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>)


481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
# File 'lib/graphql/schema/field.rb', line 481

def extras(new_extras = nil)
  if new_extras.nil?
    # Read the value
    field_extras = @extras
    if @resolver_class && !@resolver_class.extras.empty?
      field_extras + @resolver_class.extras
    else
      field_extras
    end
  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:



802
803
804
805
806
807
808
809
810
# File 'lib/graphql/schema/field.rb', line 802

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_default_page_size?Boolean

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

Returns:

  • (Boolean)

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



590
591
592
# File 'lib/graphql/schema/field.rb', line 590

def has_default_page_size?
  !NOT_CONFIGURED.equal?(@default_page_size) || (@resolver_class && @resolver_class.has_default_page_size?)
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.



574
575
576
# File 'lib/graphql/schema/field.rb', line 574

def has_max_page_size?
  !NOT_CONFIGURED.equal?(@max_page_size) || (@resolver_class && @resolver_class.has_max_page_size?)
end

#inspectObject



83
84
85
# File 'lib/graphql/schema/field.rb', line 83

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

#introspection?Boolean

Returns Is this field a predefined introspection field?.

Returns:

  • (Boolean)

    Is this field a predefined introspection field?



79
80
81
# File 'lib/graphql/schema/field.rb', line 79

def introspection?
  @introspection
end

#max_page_sizeInteger?

Returns Applied to connections if #has_max_page_size?.

Returns:



579
580
581
582
583
584
585
586
587
# File 'lib/graphql/schema/field.rb', line 579

def max_page_size
  if !NOT_CONFIGURED.equal?(@max_page_size)
    @max_page_size
  elsif @resolver_class && @resolver_class.has_max_page_size?
    @resolver_class.max_page_size
  else
    nil
  end
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?



210
211
212
# File 'lib/graphql/schema/field.rb', line 210

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)



60
61
62
63
64
65
66
67
68
# File 'lib/graphql/schema/field.rb', line 60

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, query_ctx) ⇒ Object

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

Parameters:



696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
# File 'lib/graphql/schema/field.rb', line 696

def resolve(object, args, query_ctx)
  # Unwrap the GraphQL object to get the application object.
  application_object = object.object
  method_receiver = nil
  method_to_call = nil
  method_args = nil

  @own_validators && Schema::Validator.validate!(validators, application_object, query_ctx, args)

  query_ctx.query.after_lazy(self.authorized?(application_object, args, query_ctx)) do |is_authorized|
    if is_authorized
      with_extensions(object, args, query_ctx) do |obj, ruby_kwargs|
        method_args = ruby_kwargs
        if @resolver_class
          if obj.is_a?(GraphQL::Schema::Object)
            obj = obj.object
          end
          obj = @resolver_class.new(object: obj, context: query_ctx, field: self)
        end

        inner_object = obj.object

        if !NOT_CONFIGURED.equal?(@hash_key)
          hash_value = if inner_object.is_a?(Hash)
            inner_object.key?(@hash_key) ? inner_object[@hash_key] : inner_object[@hash_key_str]
          elsif inner_object.respond_to?(:[])
            inner_object[@hash_key]
          else
            nil
          end
          if hash_value == false
            hash_value
          else
            hash_value || (@fallback_value != NOT_CONFIGURED ? @fallback_value : nil)
          end
        elsif obj.respond_to?(resolver_method)
          method_to_call = resolver_method
          method_receiver = obj
          # Call the method with kwargs, if there are any
          if !ruby_kwargs.empty?
            obj.public_send(resolver_method, **ruby_kwargs)
          else
            obj.public_send(resolver_method)
          end
        elsif inner_object.is_a?(Hash)
          if @dig_keys
            inner_object.dig(*@dig_keys)
          elsif inner_object.key?(@method_sym)
            inner_object[@method_sym]
          elsif inner_object.key?(@method_str) || !inner_object.default_proc.nil?
            inner_object[@method_str]
          elsif @fallback_value != NOT_CONFIGURED
            @fallback_value
          else
            nil
          end
        elsif inner_object.respond_to?(@method_sym)
          method_to_call = @method_sym
          method_receiver = obj.object
          if !ruby_kwargs.empty?
            inner_object.public_send(@method_sym, **ruby_kwargs)
          else
            inner_object.public_send(@method_sym)
          end
        elsif @fallback_value != NOT_CONFIGURED
          @fallback_value
        else
          raise <<-ERR
        Failed to implement #{@owner.graphql_name}.#{@name}, tried:

        - `#{obj.class}##{resolver_method}`, which did not exist
        - `#{inner_object.class}##{@method_sym}`, which did not exist
        - Looking up hash key `#{@method_sym.inspect}` or `#{@method_str.inspect}` on `#{inner_object}`, but it wasn't a Hash

        To implement this field, define one of the methods above (and check for typos), or supply a `fallback_value`.
        ERR
        end
      end
    else
      raise GraphQL::UnauthorizedFieldError.new(object: application_object, type: object.class, context: query_ctx, field: self)
    end
  end
rescue GraphQL::UnauthorizedFieldError => err
  err.field ||= self
  begin
    query_ctx.schema.unauthorized_field(err)
  rescue GraphQL::ExecutionError => err
    err
  end
rescue GraphQL::UnauthorizedError => err
  begin
    query_ctx.schema.unauthorized_object(err)
  rescue GraphQL::ExecutionError => err
    err
  end
rescue ArgumentError
  if method_receiver && method_to_call
    assert_satisfactory_implementation(method_receiver, method_to_call, method_args)
  end
  # if the line above doesn't raise, re-raise
  raise
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



74
75
76
# File 'lib/graphql/schema/field.rb', line 74

def resolver
  @resolver_class
end

#resolver_methodSymbol

Returns The method on the type to look up.

Returns:

  • (Symbol)

    The method on the type to look up



36
37
38
39
40
41
42
# File 'lib/graphql/schema/field.rb', line 36

def resolver_method
  if @resolver_class
    @resolver_class.resolver_method
  else
    @resolver_method
  end
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



169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
# File 'lib/graphql/schema/field.rb', line 169

def scoped?
  if !@scope.nil?
    # The default was overridden
    @scope
  elsif @return_type_expr
    # Detect a list return type, but don't call `type` since that may eager-load an otherwise lazy-loaded type
    @return_type_expr.is_a?(Array) ||
      (@return_type_expr.is_a?(String) && @return_type_expr.include?("[")) ||
      connection?
  elsif @resolver_class
    resolver_type = @resolver_class.type_expr
    resolver_type.is_a?(Array) ||
      (resolver_type.is_a?(String) && resolver_type.include?("[")) ||
      connection?
  else
    false
  end
end

#visible?(context) ⇒ Boolean

Returns:

  • (Boolean)


639
640
641
642
643
644
645
# File 'lib/graphql/schema/field.rb', line 639

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