Class: GraphQL::Schema::Field
- Inherits:
-
Object
- Object
- GraphQL::Schema::Field
- Extended by:
- FindInheritedValue
- Includes:
- EmptyObjects, Member::HasArguments, Member::HasArguments::FieldConfigured, Member::HasAstNode, Member::HasAuthorization, 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
Overview
Field definitions are the primary way to expose data from an object type. Keep field-specific behavior and examples here; the guide is only an entry point for the broader fields documentation.
Object fields expose data about that object or connect the object to other objects. You can add fields to your object types with the field(...) class method, for example:
field :name, String, "The unique name of this list", null: false
Objects and Interfaces have fields.
The different elements of field definition are addressed below:
- Names identify the field in GraphQL
- Return types say what kind of data this field returns
- Documentation includes description, comments and deprecation notes
- Resolution behavior hooks up the GraphQL field to Ruby code
- Arguments allow fields to take input when they're queried
- Extra field metadata for low-level access to the GraphQL-Ruby runtime
- Add default values for field parameters
Field Names
A field's name is provided as the first argument or as the name: option:
field :team_captain, ...
# or:
field ..., name: :team_captain
Under the hood, GraphQL-Ruby camelizes field names, so field :team_captain, ... would be { teamCaptain } in GraphQL. You can disable this behavior by adding camelize: false to your field definition or to the default field options.
The field's name is also used as the basis of field resolution.
Field Return Type
The second argument to field(...) is the return type. This can be:
- A built-in GraphQL type (
Integer,Float,String,ID, orBoolean) - A GraphQL type from your application
- An array of any of the above, which denotes a list type.
Nullability is expressed with the null: keyword:
null: true(default) means that the field may returnnilnull: falsemeans the field is non-nullable; it may not returnnil. If the implementation returnsnil, GraphQL-Ruby will return an error to the client.
Additionally, list types maybe nullable by adding [..., null: true] to the definition.
Here are some examples:
field :name, String # `String`, may return a `String` or `nil`
field :id, ID, null: false # `ID!`, always returns an `ID`, never `nil`
field :teammates, [Types::User], null: false # `[User!]!`, always returns a list containing `User`s
field :scores, [Integer, null: true] # `[Int]`, may return a list or `nil`, the list may contain a mix of `Integer`s and `nil`s
Field Documentation
Fields may be documented with a description, comment and may be deprecated.
Descriptions can be added with the field(...) method as a positional argument, a keyword argument, or inside the block:
# 3rd positional argument
field :name, String, "The name of this thing", null: false
# `description:` keyword
field :name, String, null: false,
description: "The name of this thing"
# inside the block
field :name, String, null: false do
description "The name of this thing"
end
Comments can be added with the field(...) method as a keyword argument, or inside the block:
# `comment:` keyword
field :name, String, null: false, comment: "Rename to full name"
# inside the block
field :name, String, null: false do
comment "Rename to full name"
end
Generates field name with comment above "Rename to full name" above.
type Foo {
# Rename to full name
name: String!
}
Deprecated fields can be marked by adding a deprecation_reason: keyword argument:
field :email, String,
deprecation_reason: "Users may have multiple emails, use `User.emails` instead."
Fields with a deprecation_reason: will appear as "deprecated" in GraphiQL.
Field Resolution
In general, fields return Ruby values corresponding to their GraphQL return types. For example, a field with the return type String should return a Ruby string, and a field with the return type [User!]! should return a Ruby array with zero or more User objects in it.
By default, fields return values by:
- Trying to call a method on the underlying object; OR
- If the underlying object is a
Hash, lookup a key in that hash. - An optional
:fallback_valuecan be supplied that will be used if the above fail.
The method name or hash key corresponds to the field name, so in this example:
field :top_score, Integer, null: false
The default behavior is to look for a #top_score method, or lookup a Hash key, :top_score (symbol) or "top_score" (string).
You can override the method name with the method: keyword, or override the hash key(s) with the hash_key: or dig: keyword, for example:
# Use the `#best_score` method to resolve this field
field :top_score, Integer, null: false,
method: :best_score
# Lookup `hash["allPlayers"]` to resolve this field
field :players, [User], null: false,
hash_key: "allPlayers"
# Use the `#dig` method on the hash with `:nested` and `:movies` keys
field :movies, [Movie], null: false,
dig: [:nested, :movies]
To pass-through the underlying object without calling a method on it, you can use method: :itself:
field :player, User, null: false,
method: :itself
This is equivalent to:
field :player, User, null: false
def player
object
end
If you don't want to delegate to the underlying object, you can define a method for each field:
# Use the custom method below to resolve this field
field :total_games_played, Integer, null: false
def total_games_played
object.games.count
end
Inside the method, you can access some helper methods:
objectis the underlying application object (formerlyobjto resolve functions)contextis the query context (passed ascontext:when executing queries, formerlyctxto resolve functions)
Additionally, when you define arguments (see below), they're passed to the method definition, for example:
# Call the custom method with incoming arguments
field :current_winning_streak, Integer, null: false do
argument :include_ties, Boolean, required: false, default_value: false
end
def current_winning_streak(include_ties:)
# Business logic goes here
end
As the examples above show, by default the custom method name must match the field name. If you want to use a different custom method, the resolver_method option is available:
# Use the custom method with a non-default name below to resolve this field
field :total_games_played, Integer, null: false, resolver_method: :games_played
def games_played
object.games.count
end
resolver_method has two main use cases:
- resolver re-use between multiple fields
- dealing with method conflicts (specifically if you have fields named
contextorobject)
Note that resolver_method cannot be used in combination with method or hash_key.
Field Arguments
Arguments allow fields to take input to their resolution. For example:
- A
search()field may take aterm:argument, which is the query to use for searching, egsearch(term: "GraphQL") - A
user()field may take anid:argument, which specifies which user to find, eguser(id: 1) - An
attachments()field may take atype:argument, which filters the result by file type, egattachments(type: PHOTO)
Read more in the Arguments guide
Extra Field Metadata
Inside a field method, you can access some low-level objects from the GraphQL-Ruby runtime. Be warned, these APIs are subject to change, so check the changelog when updating.
A few extras are available:
ast_nodegraphql_name(the field's name)owner(the type that this field belongs to)lookahead(see Lookahead)execution_errors, whose#add(err_or_msg)method should be used for adding errorsargument_details(Interpreter only), an instance of GraphQL::Execution::Interpreter::Arguments with argument metadataparent(the previousobjectin the query)- Custom extras, see below
To inject them into your field method, first, add the extras: option to the field definition:
field :my_field, String, null: false, extras: [:ast_node]
Then add ast_node: keyword to the method signature:
def my_field(ast_node:)
# ...
end
At runtime, the requested runtime object will be passed to the field.
Custom extras are also possible. Any method on your field class can be passed to extras: [...], and the value will be injected into the method. For example, extras: [:owner] will inject the object type who owns the field. Any new methods on your custom field class may be used, too.
Field Parameter Default Values
The field method requires you to pass null: keyword argument to determine whether the field is nullable or not. For another field you may want to override camelize, which is true by default. You can override this behavior by adding a custom field with overwritten camelize option, which is true by default.
class CustomField < GraphQL::Schema::Field
# Add `null: false` and `camelize: false` which provide default values
# in case the caller doesn't pass anything for those arguments.
# **kwargs is a catch-all that will get everything else
def initialize(*args, null: false, camelize: false, **kwargs, &block)
# Then, call super _without_ any args, where Ruby will take
# _all_ the args originally passed to this method and pass it to the super method.
super
end
end
To use CustomField in your Objects and Interfaces, you'll need to register it as a field_class on those classes. See Customizing Fields for more information on how to do so.
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
-
#description(text = nil) ⇒ Object
Parameters.
-
#dig_keys ⇒ Object
readonly
Returns the value of attribute dig_keys.
-
#dynamic_introspection ⇒ Object
Returns the value of attribute dynamic_introspection.
-
#execution_mode ⇒ Object
readonly
:nodoc:.
-
#execution_mode_key ⇒ Object
readonly
:nodoc:.
-
#hash_key ⇒ Object
readonly
Returns the value of attribute hash_key.
-
#method_str ⇒ Object
readonly
Returns.
-
#method_sym ⇒ Object
readonly
Returns.
-
#name ⇒ Object
(also: #graphql_name)
readonly
Returns.
-
#original_name ⇒ Object
readonly
Returns.
-
#owner ⇒ Object
Returns.
-
#relay_node_field ⇒ Object
readonly
Returns.
-
#relay_nodes_field ⇒ Object
readonly
Returns.
-
#subscription_scope ⇒ Object
Returns.
-
#trace ⇒ Object
readonly
Returns.
-
#type(new_type = NOT_CONFIGURED) ⇒ Object
Get or set the return type of this field.
Attributes included from Member::HasAstNode
Class Method Summary collapse
-
.connection_extension(new_extension_class = nil) ⇒ Object
This extension is applied to fields when connection? is true.
Instance Method Summary collapse
- #authorized?(object, args, context) ⇒ Boolean
- #authorizes?(context) ⇒ Boolean
-
#broadcastable? ⇒ Boolean
If true, subscription updates with this field can be shared between viewers See
GraphQL::Subscriptions::BroadcastAnalyzer. - #calculate_complexity(query:, nodes:, child_complexity:) ⇒ Object
-
#comment(text = nil) ⇒ Object
Parameters.
- #complexity(new_complexity = nil) ⇒ Object
-
#connection? ⇒ Boolean
Can be set with
connection: true|falseor inferred from a type name ending in*Connection. -
#default_page_size ⇒ Object
Returns.
-
#deprecation_reason ⇒ Object
Returns.
- #directives ⇒ Object
-
#ensure_loaded ⇒ Object
Calls the definition block, if one was given.
-
#extension(extension_class, **options) ⇒ Object
Add
extensionto this field, initialized withoptionsif provided. -
#extensions(new_extensions = nil) ⇒ Object
Read extension instances from this field, or add new classes/options to be initialized on this field.
-
#extras(new_extras = nil) ⇒ Object
Read extras (as symbols) from this field, or add new extras to be opted into by this field's resolver.
-
#fetch_extra(extra_name, ctx) ⇒ Object
Parameters.
- #freeze ⇒ Object
-
#has_default_page_size? ⇒ Boolean
Returns.
-
#has_max_page_size? ⇒ Boolean
Returns.
-
#initialize(type: nil, name: nil, owner: nil, null: nil, description: NOT_CONFIGURED, comment: NOT_CONFIGURED, deprecation_reason: nil, method: nil, resolve_legacy_instance_method: nil, resolve_static: nil, resolve_each: nil, resolve_batch: nil, hash_key: nil, dig: nil, resolver_method: nil, connection: nil, max_page_size: NOT_CONFIGURED, default_page_size: NOT_CONFIGURED, 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, scope: nil, introspection: false, camelize: true, trace: nil, complexity: nil, dataload: nil, ast_node: nil, &definition_block) ⇒ Field
constructor
Parameters.
- #inspect ⇒ Object
-
#introspection? ⇒ Boolean
Returns.
-
#max_page_size ⇒ Object
Returns.
-
#method_conflict_warning? ⇒ Boolean
Returns.
-
#owner_type ⇒ Object
Returns.
-
#resolve(object, args, query_ctx) ⇒ Object
This method is called by the interpreter for each field.
-
#resolver ⇒ Object
(also: #mutation)
Returns.
-
#resolver_method ⇒ Object
Returns.
- #run_next_extensions_before_resolve(objs, args, ctx, extended, idx: 0, &block) ⇒ Object
-
#scoped? ⇒ Boolean
Returns.
- #visible?(context) ⇒ Boolean
Methods included from FindInheritedValue
Methods included from Member::HasDeprecationReason
Methods included from Member::HasDirectives
add_directive, #directive, extended, get_directives, #inherited, #remove_directive, remove_directive
Methods included from Member::HasValidators
extended, #validates, #validators
Methods included from Member::HasPath
Methods included from Member::HasAuthorization
Methods included from Member::HasAstNode
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, extended, #get_argument, included, #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, resolve_legacy_instance_method: nil, resolve_static: nil, resolve_each: nil, resolve_batch: nil, hash_key: nil, dig: nil, resolver_method: nil, connection: nil, max_page_size: NOT_CONFIGURED, default_page_size: NOT_CONFIGURED, 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, scope: nil, introspection: false, camelize: true, trace: nil, complexity: nil, dataload: nil, ast_node: nil, &definition_block) ⇒ Field
Parameters
name(Symbol) — The underscore-cased version of this field name (will be camelized for the GraphQL API)type(Class, GraphQL::BaseType, Array) — The return type of this fieldowner(Class) — The type that this field belongs tonull(Boolean) — (defaults totrue)trueif this field may returnnull,falseif it is nevernulldescription(String) — Field descriptioncomment(String) — Field commentdeprecation_reason(String) — If present, the field is marked "deprecated" with this messagemethod(Symbol) — The method to call on the underlying object to resolve this field (defaults toname)hash_key(String, Symbol) — The hash key to lookup on the underlying object (if its a Hash) to resolve this field (defaults tonameorname.to_s)dig(Array<String, Symbol>) — The nested hash keys to lookup on the underlying hash to resolve this field using digresolver_method(Symbol) — The method on the type to call to resolve this field (defaults toname)connection(Boolean) —trueif this field should get automagic connection behavior; default is to infer by*Connectionin the return type nameconnection_extension(Class) — The extension to add, to implement connections. Ifnil, no extension is added.resolve_static(Symbol, true, nil) — Used bySchema.execute_nextto produce a single value, shared by all objects which resolve this field. Called on the owner type class withcontext, **argumentsresolve_batch(Symbol, true, nil) — Used bySchema.execute_nextmapobjectsto a same-sized Array of results. Called on the owner type class withobjects, context, **arguments.resolve_each(Symbol, true, nil) — Used bySchema.execute_nextto get a value value for each item. Called on the owner type class withobject, context, **arguments.resolve_legacy_instance_method(Symbol, true, nil) — Used bySchema.execute_nextto get a value value for each item. Calls an instance method on the object type class.dataload(Class, Hash) — Shorthand for making dataloader callsmax_page_size(Integer, nil) — For connections, the maximum number of items to return from this field, ornilto allow unlimited results.default_page_size(Integer, nil) — For connections, the default number of items to return from this field, ornilto return unlimited results.introspection(Boolean) — If true, this field will be marked as#introspection?and the name may begin with__resolver_class(Class) — (Private) A Schema::Resolver which this field was derived from. Useresolver:to create a field with a resolver.arguments({String=>GraphQL::Schema::Argument, Hash}) — Arguments for this field (may be added in the block, also)camelize(Boolean) — If true, the field name will be camelized when building the schemacomplexity(Numeric) — When provided, set the complexity for this fieldscope(Boolean) — If true, the return type's.scope_itemsmethod will be called on the return valuesubscription_scope(Symbol, String) — A key incontextwhich will be used to scope subscription payloadsextensions(Array<Class, Hash<Class => Object>>) — Named extensions to apply to this field (see also extension)directives(Hash{Class => Hash}) — Directives to apply to this fieldtrace(Boolean) — If true, a GraphQL::Tracing tracer will measure this scalar fieldbroadcastable(Boolean) — Whether or not this field can be distributed in subscription broadcastsast_node(Language::Nodes::FieldDefinition, nil) — If this schema was parsed from definition, this AST node defined the fieldmethod_conflict_warning(Boolean) — If false, skip the warning if this field's method conflicts with a built-in methodvalidates(Array<Hash>) — Configurations for validating this fieldfallback_value(Object) — A fallback value if the method is not defineddynamic_introspection(Boolean) — (Private, used by GraphQL-Ruby)relay_node_field(Boolean) — (Private, used by GraphQL-Ruby)relay_nodes_field(Boolean) — (Private, used by GraphQL-Ruby)extras(Array<:ast_node, :parent, :lookahead, :owner, :execution_errors, :graphql_name, :argument_details, Symbol>) — Extra arguments to be injected into the resolver for this fielddefinition_block(Proc) — an additional block for configuring the field. Receive the field as a block param, or, if no block params are defined, then the block isinstance_eval'd on the new Field.
:call-seq:
initialize(Class | GraphQL::BaseType | Array type:, Symbol name:, Class owner:, bool null:, String description:, String comment:, String deprecation_reason:, Symbol method:, Symbol | true | nil resolve_legacy_instance_method:, Symbol | true | nil resolve_static:, Symbol | true | nil resolve_each:, Symbol | true | nil resolve_batch:, String | Symbol hash_key:, Array[String | Symbol] dig:, Symbol resolver_method:, bool connection:, Integer | nil max_page_size:, Integer | nil default_page_size:, Array[:ast_node | :parent | :lookahead | :owner | :execution_errors | :graphql_name | :argument_details | Symbol] extras:, Array[Class | Hash[Class, Object]] extensions:, Class connection_extension:, Class resolver_class:, Symbol | String subscription_scope:, bool relay_node_field:, bool relay_nodes_field:, bool method_conflict_warning:, bool broadcastable:, {String=>GraphQL::Schema::Argument | Hash} arguments:, Hash[Class, Hash] directives:, Array[Hash] validates:, Object fallback_value:, bool dynamic_introspection:, bool scope:, bool introspection:, bool camelize:, bool trace:, Numeric complexity:, Class | Hash dataload:, Language::Nodes::FieldDefinition | nil ast_node:, Proc &definition_block)
573 574 575 576 577 578 579 580 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 607 608 609 610 611 612 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 638 639 640 641 642 643 644 645 646 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 690 691 692 693 694 695 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 |
# File 'lib/graphql/schema/field.rb', line 573 def initialize( type: nil, name: nil, owner: nil, null: nil, description: NOT_CONFIGURED, comment: NOT_CONFIGURED, deprecation_reason: nil, method: nil, resolve_legacy_instance_method: nil, resolve_static: nil, resolve_each: nil, resolve_batch: nil, hash_key: nil, dig: nil, resolver_method: nil, connection: nil, max_page_size: NOT_CONFIGURED, default_page_size: NOT_CONFIGURED, 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, # Keywords below this line must have literal defaults (`nil`, `true`, `false`, a number or a symbol). # Ruby uses a 31-bit bitmap to track which keywords with non-literal defaults were given. # If one comes after the 31st keyword, Ruby allocates a Hash on every call. dynamic_introspection: false, scope: nil, introspection: false, camelize: true, trace: nil, complexity: nil, dataload: nil, ast_node: nil, &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 @name = -(camelize ? Member::BuildType.camelize(name_s) : name_s) NameValidator.validate!(@name) @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 if resolve_static @execution_mode = :resolve_static @execution_mode_key = resolve_static == true ? @method_sym : resolve_static elsif resolve_batch @execution_mode = :resolve_batch @execution_mode_key = resolve_batch == true ? @method_sym : resolve_batch elsif resolve_each @execution_mode = :resolve_each @execution_mode_key = resolve_each == true ? @method_sym : resolve_each elsif hash_key @execution_mode = :hash_key @execution_mode_key = hash_key elsif dig @execution_mode = :dig @execution_mode_key = dig elsif resolver_class @execution_mode = :resolver_class @execution_mode_key = resolver_class elsif resolve_legacy_instance_method @execution_mode = :resolve_legacy_instance_method @execution_mode_key = resolve_legacy_instance_method == true ? @method_sym : resolve_legacy_instance_method elsif dataload @execution_mode = :dataload @execution_mode_key = dataload else @execution_mode = :direct_send @execution_mode_key = @method_sym end @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: NOT_CONFIGURED.equal?(connection_extension) ? self.class.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, )| self.directive(dir_class, **) 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) ⇒ Object
Parameters
text(String)
Returns
String
:call-seq:
description(String text) -> String
818 819 820 821 822 823 824 825 826 827 828 |
# File 'lib/graphql/schema/field.rb', line 818 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_keys ⇒ Object (readonly)
Returns the value of attribute dig_keys.
311 312 313 |
# File 'lib/graphql/schema/field.rb', line 311 def dig_keys @dig_keys end |
#dynamic_introspection ⇒ Object
Returns the value of attribute dynamic_introspection.
787 788 789 |
# File 'lib/graphql/schema/field.rb', line 787 def dynamic_introspection @dynamic_introspection end |
#execution_mode ⇒ Object (readonly)
:nodoc:
764 765 766 |
# File 'lib/graphql/schema/field.rb', line 764 def execution_mode @execution_mode end |
#execution_mode_key ⇒ Object (readonly)
:nodoc:
764 765 766 |
# File 'lib/graphql/schema/field.rb', line 764 def execution_mode_key @execution_mode_key end |
#hash_key ⇒ Object (readonly)
Returns the value of attribute hash_key.
310 311 312 |
# File 'lib/graphql/schema/field.rb', line 310 def hash_key @hash_key end |
#method_str ⇒ Object (readonly)
Returns
String— Method or hash key on the underlying object to look up
308 309 310 |
# File 'lib/graphql/schema/field.rb', line 308 def method_str @method_str end |
#method_sym ⇒ Object (readonly)
Returns
Symbol— Method or hash key on the underlying object to look up
303 304 305 |
# File 'lib/graphql/schema/field.rb', line 303 def method_sym @method_sym end |
#name ⇒ Object (readonly) Also known as: graphql_name
Returns
String— the GraphQL name for this field, camelized unlesscamelize: falseis provided
295 296 297 |
# File 'lib/graphql/schema/field.rb', line 295 def name @name end |
#original_name ⇒ Object (readonly)
Returns
Symbol— the original name of the field, passed in by the user
382 383 384 |
# File 'lib/graphql/schema/field.rb', line 382 def original_name @original_name end |
#owner ⇒ Object
Returns
Class— The thing this field was defined on (type, mutation, resolver)
361 362 363 |
# File 'lib/graphql/schema/field.rb', line 361 def owner @owner end |
#relay_node_field ⇒ Object (readonly)
Returns
Object— Boolean
512 513 514 |
# File 'lib/graphql/schema/field.rb', line 512 def relay_node_field @relay_node_field end |
#relay_nodes_field ⇒ Object (readonly)
Returns
Object— Boolean
516 517 518 |
# File 'lib/graphql/schema/field.rb', line 516 def relay_nodes_field @relay_nodes_field end |
#subscription_scope ⇒ Object
Returns
String, nil
:call-seq:
subscription_scope() -> String | nil
421 422 423 |
# File 'lib/graphql/schema/field.rb', line 421 def subscription_scope @subscription_scope || (@resolver_class.respond_to?(:subscription_scope) ? @resolver_class.subscription_scope : nil) end |
#trace ⇒ Object (readonly)
Returns
Boolean— Apply tracing to this field? (Default: skip scalars, this is the override value)
413 414 415 |
# File 'lib/graphql/schema/field.rb', line 413 def trace @trace end |
#type(new_type = NOT_CONFIGURED) ⇒ Object
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
new_type(Module, GraphQL::Schema::NonNull, GraphQL::Schema::List) — A GraphQL return type
Returns
Module, GraphQL::Schema::NonNull, GraphQL::Schema::List, nil— the configured type for this field
:call-seq:
type(Module | GraphQL::Schema::NonNull | GraphQL::Schema::List new_type) -> Module | GraphQL::Schema::NonNull | GraphQL::Schema::List | nil
1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 |
# File 'lib/graphql/schema/field.rb', line 1132 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.}", err.backtrace end |
Class Method Details
.connection_extension(new_extension_class = nil) ⇒ Object
This extension is applied to fields when connection? is true.
You can override it in your base field definition.
Returns
Class— A FieldExtension subclass for implementing pagination behavior.
Examples
Example: Configuring a custom extension
class Types::BaseField < GraphQL::Schema::Field
connection_extension(MyCustomExtension)
end
:call-seq:
connection_extension(new_extension_class) -> Class
501 502 503 504 505 506 507 |
# File 'lib/graphql/schema/field.rb', line 501 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 |
Instance Method Details
#authorized?(object, args, context) ⇒ Boolean
1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 |
# File 'lib/graphql/schema/field.rb', line 1172 def (object, args, context) if @resolver_class # The resolver _instance_ will check itself during `resolve()` @resolver_class.(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.(object, application_arg_value, context) return false end end end end true end end |
#authorizes?(context) ⇒ Boolean
1166 1167 1168 1169 1170 |
# File 'lib/graphql/schema/field.rb', line 1166 def (context) method(:authorized?).owner != GraphQL::Schema::Field || ((args = context.types.arguments(self)) && (args.any? { |a| a.(context) })) || (@resolver_class&.(context)) || false end |
#broadcastable? ⇒ Boolean
If true, subscription updates with this field can be shared between viewers
See GraphQL::Subscriptions::BroadcastAnalyzer.
Returns
Boolean, nil
:call-seq:
broadcastable?() -> bool | nil
798 799 800 801 802 803 804 805 806 |
# File 'lib/graphql/schema/field.rb', line 798 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
970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 |
# File 'lib/graphql/schema/field.rb', line 970 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) return child_complexity 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 elsif max_possible_page_size < 0 # Pagination returns no items for a negative `first:` or `last:`, so it mustn't subtract from the total. max_possible_page_size = 0 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) # `QueryComplexity` doesn't add skipped introspection fields to `child_complexity`, # so they must not be subtracted from it here, either. count_introspection_fields = query.schema.max_complexity_count_introspection_fields lookahead.selections.each do |next_lookahead| next if !count_introspection_fields && next_lookahead.field.introspection? # 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 if count_introspection_fields += next_lookahead.selections.size else += next_lookahead.selections.count { |s| !s.field.introspection? } end 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) ⇒ Object
Parameters
text(String)
Returns
String, nil
:call-seq:
comment(String text) -> String | nil
840 841 842 843 844 845 846 847 848 849 850 |
# File 'lib/graphql/schema/field.rb', line 840 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
1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 |
# File 'lib/graphql/schema/field.rb', line 1031 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
:call-seq:
connection?() -> bool
434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 |
# File 'lib/graphql/schema/field.rb', line 434 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_size ⇒ Object
Returns
Integer, nil— Applied to connections if has default page size?
:call-seq:
default_page_size() -> Integer | nil
1097 1098 1099 1100 1101 1102 1103 1104 1105 |
# File 'lib/graphql/schema/field.rb', line 1097 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 |
#deprecation_reason ⇒ Object
Returns
String, nil
:call-seq:
deprecation_reason() -> String | nil
333 334 335 |
# File 'lib/graphql/schema/field.rb', line 333 def deprecation_reason super || @resolver_class&.deprecation_reason end |
#directives ⇒ Object
337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 |
# File 'lib/graphql/schema/field.rb', line 337 def directives if @resolver_class && !(r_dirs = @resolver_class.directives).empty? if !(own_dirs = super).empty? new_dirs = own_dirs.dup r_dirs.each do |r_dir| if r_dir.class.repeatable? || ( (r_dir_name = r_dir.graphql_name) && (!new_dirs.any? { |d| d.graphql_name == r_dir_name }) ) new_dirs << r_dir end end new_dirs else r_dirs end else super end end |
#ensure_loaded ⇒ Object
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
773 774 775 776 777 778 779 780 781 782 783 784 785 |
# File 'lib/graphql/schema/field.rb', line 773 def ensure_loaded # :nodoc: if @definition_block if @definition_block.arity == 1 @definition_block.call(self) else instance_exec(self, &@definition_block) end self.extensions.each(&:after_define_apply) @call_after_define = true @definition_block = nil end self end |
#extension(extension_class, **options) ⇒ Object
Add extension to this field, initialized with options if provided.
Examples
Example: adding an extension
extension(MyExtensionClass)
Example: adding an extension with options
extension(MyExtensionClass, filter: true)
Parameters
extension_class(Class) — subclass of Schema::FieldExtensionoptions(Hash) — if provided, given asoptions:when initializingextension.
Returns
void
:call-seq:
extension(Class extension_class, Hash **options) -> void
927 928 929 930 931 932 933 934 935 936 937 |
# File 'lib/graphql/schema/field.rb', line 927 def extension(extension_class, **) extension_inst = extension_class.new(field: self, 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) ⇒ Object
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
Example: adding an extension
extensions([MyExtensionClass])
Example: adding multiple extensions
extensions([MyExtensionClass, AnotherExtensionClass])
Example: 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
Array<GraphQL::Schema::FieldExtension>— extensions to apply to this field
:call-seq:
extensions(new_extensions) -> Array[GraphQL::Schema::FieldExtension]
886 887 888 889 890 891 892 893 894 895 896 897 898 |
# File 'lib/graphql/schema/field.rb', line 886 def extensions(new_extensions = nil) if new_extensions new_extensions.each do |extension_config| if extension_config.is_a?(Hash) extension_class, = *extension_config.to_a[0] self.extension(extension_class, **) else self.extension(extension_config) end end end @extensions end |
#extras(new_extras = nil) ⇒ Object
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>) — Add extras to this field
Returns
Array<Symbol>
:call-seq:
extras(Array[Symbol] new_extras) -> Array[Symbol]
952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 |
# File 'lib/graphql/schema/field.rb', line 952 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
ctx(GraphQL::Query::Context)
:call-seq:
fetch_extra(extra_name, GraphQL::Query::Context ctx)
1338 1339 1340 1341 1342 1343 1344 1345 1346 |
# File 'lib/graphql/schema/field.rb', line 1338 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 |
#freeze ⇒ Object
1107 1108 1109 1110 1111 1112 1113 |
# File 'lib/graphql/schema/field.rb', line 1107 def freeze type owner_type arguments_statically_coercible? connection? super end |
#has_default_page_size? ⇒ Boolean
Returns
Boolean— True if this field's default page size should override the schema default.
:call-seq:
has_default_page_size?() -> bool
1087 1088 1089 |
# File 'lib/graphql/schema/field.rb', line 1087 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
Boolean— True if this field's max page size should override the schema default.
:call-seq:
has_max_page_size?() -> bool
1061 1062 1063 |
# File 'lib/graphql/schema/field.rb', line 1061 def has_max_page_size? !NOT_CONFIGURED.equal?(@max_page_size) || (@resolver_class && @resolver_class.has_max_page_size?) end |
#inspect ⇒ Object
404 405 406 |
# File 'lib/graphql/schema/field.rb', line 404 def inspect "#<#{self.class} #{path}#{!all_argument_definitions.empty? ? "(...)" : ""}: #{type.to_type_signature}>" end |
#introspection? ⇒ Boolean
Returns
Boolean— Is this field a predefined introspection field?
:call-seq:
introspection?() -> bool
400 401 402 |
# File 'lib/graphql/schema/field.rb', line 400 def introspection? @introspection end |
#max_page_size ⇒ Object
Returns
Integer, nil— Applied to connections if has max page size?
:call-seq:
max_page_size() -> Integer | nil
1071 1072 1073 1074 1075 1076 1077 1078 1079 |
# File 'lib/graphql/schema/field.rb', line 1071 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
Boolean— Should we warn if this field's name conflicts with a built-in method?
:call-seq:
method_conflict_warning?() -> bool
524 525 526 |
# File 'lib/graphql/schema/field.rb', line 524 def method_conflict_warning? @method_conflict_warning end |
#owner_type ⇒ Object
Returns
Class— The GraphQL type this field belongs to. (For fields defined on mutations, it's the payload type)
:call-seq:
owner_type() -> Class
369 370 371 372 373 374 375 376 377 |
# File 'lib/graphql/schema/field.rb', line 369 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
object(GraphQL::Schema::Object) — An instance of some type class, wrapping an application objectargs(Hash) — A symbol-keyed hash of Ruby keyword arguments. (Empty if no args)ctx(GraphQL::Query::Context)
:call-seq:
resolve(GraphQL::Schema::Object object, Hash args, query_ctx)
1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 |
# File 'lib/graphql/schema/field.rb', line 1227 def resolve(object, args, query_ctx) # Unwrap the GraphQL object to get the application object. application_object = object.object method_receiver = nil #: untyped method_to_call = nil #: untyped method_args = nil #: untyped @own_validators && Schema::Validator.validate!(validators, application_object, query_ctx, args) query_ctx.query.after_lazy(self.(application_object, args, query_ctx)) do || if 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.(err) rescue GraphQL::ExecutionError => err err end rescue GraphQL::UnauthorizedError => err begin query_ctx.schema.(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 |
#resolver ⇒ Object Also known as: mutation
Returns
Class, nil— The Schema::Resolver this field was derived from, if there is one
:call-seq:
resolver() -> Class | nil
390 391 392 |
# File 'lib/graphql/schema/field.rb', line 390 def resolver @resolver_class end |
#resolver_method ⇒ Object
Returns
Symbol— The method on the type to look up
:call-seq:
resolver_method() -> Symbol
319 320 321 322 323 324 325 |
# File 'lib/graphql/schema/field.rb', line 319 def resolver_method if @resolver_class @resolver_class.resolver_method else @resolver_method end end |
#run_next_extensions_before_resolve(objs, args, ctx, extended, idx: 0, &block) ⇒ Object
1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 |
# File 'lib/graphql/schema/field.rb', line 1445 def run_next_extensions_before_resolve(objs, args, ctx, extended, idx: 0, &block) extension = @extensions[idx] if extension extension.resolve(objects: objs, arguments: args, context: ctx) do |extended_objs, extended_args, memo| if memo memos = extended.memos ||= {} memos[idx] = memo end if (extras = extension.added_extras) ae = extended.added_extras ||= [] ae.concat(extras) end extended.object = extended_objs extended.arguments = extended_args run_next_extensions_before_resolve(extended_objs, extended_args, ctx, extended, idx: idx + 1, &block) end else yield(objs, args) end end |
#scoped? ⇒ Boolean
Returns
Boolean— if true, the return type's.scope_itemsmethod will be applied to this field's return value
:call-seq:
scoped?() -> bool
462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 |
# File 'lib/graphql/schema/field.rb', line 462 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
1158 1159 1160 1161 1162 1163 1164 |
# File 'lib/graphql/schema/field.rb', line 1158 def visible?(context) if @resolver_class @resolver_class.visible?(context) else true end end |