Class: GraphQL::Schema::Argument
- Inherits:
-
Object
- Object
- GraphQL::Schema::Argument
- Includes:
- EmptyObjects, Member::HasAstNode, Member::HasAuthorization, Member::HasDeprecationReason, Member::HasDirectives, Member::HasPath, Member::HasValidators
- Defined in:
- lib/graphql/schema/argument.rb
Overview
Arguments describe the input accepted by a field or input object. Keep argument-specific behavior and examples here; the guide is only an entry point for the broader fields documentation.
Fields can take arguments as input. These can be used to determine the return value (eg, filtering search results) or to modify the application state (eg, updating the database in MutationType).
Arguments are defined with the argument helper. These arguments are passed as keyword arguments to the resolver method:
field :search_posts, [PostType], null: false do
argument :category, String
end
def search_posts(category:)
Post.where(category: category).limit(10)
end
Nullability
To make an argument optional, set required: false, and set default values for the corresponding keyword arguments:
field :search_posts, [PostType], null: false do
argument :category, String, required: false
end
def search_posts(category: nil)
if category
Post.where(category: category).limit(10)
else
Post.all.limit(10)
end
end
Be aware that if all arguments are optional and the query does not provide any arguments, then the resolver method will be called with no arguments. To prevent an ArgumentError in this case, you must either specify default values for all keyword arguments (as done in the prior example) or use the double splat operator argument in the method definition. For example:
def search_posts(**args)
if args[:category]
Post.where(category: args[:category]).limit(10)
else
Post.all.limit(10)
end
end
Default Values
Another approach is to use default_value: value to provide a default value for the argument if it is not supplied in the query.
field :search_posts, [PostType], null: false do
argument :category, String, required: false, default_value: "Programming"
end
def search_posts(category:)
Post.where(category: category).limit(10)
end
Arguments with required: false do accept null as inputs from clients. This can be surprising in resolver code, for example, an argument with Integer, required: false can sometimes be nil. In this case, you can use replace_null_with_default: true to apply the given default_value: ... when clients provide null. For example:
# Even if clients send `query: null`, the resolver will receive `"*"` for this argument:
argument :query, String, required: false, default_value: "*", replace_null_with_default: true
Finally, required: :nullable will require clients to pass the argument, although it will accept null as a valid input. For example:
# This argument _must_ be given -- send `null` if there's no other appropriate value:
argument :email_address, String, required: :nullable
Deprecation
Experimental: Deprecated arguments can be marked by adding a deprecation_reason: keyword argument:
field :search_posts, [PostType], null: false do
argument :name, String, required: false, deprecation_reason: "Use `query` instead."
argument :query, String, required: false
end
Aliasing
Use as: :alternate_name to use a different key from within your resolvers while
exposing another key to clients.
field :post, PostType, null: false do
argument :post_id, ID, as: :id
end
def post(id:)
Post.find(id)
end
Preprocessing
Provide a prepare function to modify or validate the value of an argument before the field's resolver method is executed:
field :posts, [PostType], null: false do
argument :start_date, String, prepare: ->(startDate, ctx) {
# return the prepared argument.
# raise a GraphQL::ExecutionError to halt the execution of the field and
# add the exception's message to the `errors` key.
}
end
def posts(start_date:)
# use prepared start_date
end
Automatic camelization
Arguments that are snake_cased will be camelized in the GraphQL schema. Using the example of:
field :posts, [PostType], null: false do
argument :start_year, Int
end
The corresponding GraphQL query will look like:
{
posts(startYear: 2018) {
id
}
}
To disable auto-camelization, pass camelize: false to the argument method.
field :posts, [PostType], null: false do
argument :start_year, Int, camelize: false
end
Furthermore, if your argument is already camelCased, then it will remain camelized in the GraphQL schema. However, the argument will be converted to snake_case when it is passed to the resolver method:
field :posts, [PostType], null: false do
argument :startYear, Int
end
def posts(start_year:)
# ...
end
Valid Argument Types
Only certain types are valid for arguments:
- GraphQL::Schema::Scalar, including built-in scalars (string, int, float, boolean, ID)
- GraphQL::Schema::Enum
- GraphQL::Schema::InputObject, which allows key-value pairs as input
- GraphQL::Schema::Lists of a valid input type, configured using
[...] - GraphQL::Schema::NonNulls of a valid input type (arguments are non-null by default; use
required: falseto make optional arguments)
Defined Under Namespace
Classes: InvalidDefaultValueError
Constant Summary
Constants included from EmptyObjects
EmptyObjects::EMPTY_ARRAY, EmptyObjects::EMPTY_HASH
Instance Attribute Summary collapse
-
#comment(text = nil) ⇒ Object
Returns.
-
#description(text = nil) ⇒ Object
Returns.
-
#keyword ⇒ Object
readonly
Returns.
-
#loads ⇒ Object
readonly
Returns.
-
#name ⇒ Object
(also: #graphql_name)
readonly
Returns.
-
#owner ⇒ Object
readonly
Returns.
Attributes included from Member::HasAstNode
Instance Method Summary collapse
- #authorized?(obj, value, ctx) ⇒ Boolean
- #authorized_as_type?(obj, value, ctx, as_type:) ⇒ Boolean
- #authorizes?(context) ⇒ Boolean
-
#coerce_into_values(parent_object, values, context, argument_values) ⇒ Object
:nodoc:.
-
#default_value(new_default_value = NOT_CONFIGURED) ⇒ Object
Parameters.
-
#default_value? ⇒ Boolean
Returns.
-
#deprecation_reason(text = nil) ⇒ Object
Returns.
- #deprecation_reason=(new_reason) ⇒ Object
- #freeze ⇒ Object
-
#from_resolver? ⇒ Boolean
Returns.
-
#handle_or_reraise_arg_error(context, err) ⇒ Object
When a
rescue_fromhandler returns an error object instead of raising, it must not be used as this argument's value — raise it so thatcoerce_argumentsshort-circuits resolution with it. -
#initialize(arg_name = nil, type_expr = nil, desc = nil, required: true, type: nil, name: nil, loads: nil, description: nil, comment: nil, ast_node: nil, default_value: NOT_CONFIGURED, as: nil, from_resolver: false, camelize: true, prepare: nil, owner:, validates: nil, directives: nil, deprecation_reason: nil, replace_null_with_default: false, &definition_block) ⇒ Argument
constructor
Parameters.
- #inspect ⇒ Object
- #load_and_authorize_value(load_method_owner, coerced_value, context) ⇒ Object
-
#prepare(new_prepare = NOT_CONFIGURED) ⇒ Object
Parameters.
-
#prepare_value(obj, value, context: nil) ⇒ Object
Apply the prepare configuration to
value, using methods fromobj. - #replace_null_with_default? ⇒ Boolean
- #statically_coercible? ⇒ Boolean
- #type ⇒ Object
- #type=(new_type) ⇒ Object
-
#validate_default_value ⇒ Object
:nodoc:.
- #visible?(context) ⇒ Boolean
Methods included from Member::HasValidators
extended, #validates, #validators
Methods included from Member::HasDeprecationReason
Methods included from Member::HasDirectives
add_directive, #directive, #directives, extended, get_directives, #inherited, #remove_directive, remove_directive
Methods included from Member::HasAuthorization
Methods included from Member::HasAstNode
Methods included from Member::HasPath
Constructor Details
#initialize(arg_name = nil, type_expr = nil, desc = nil, required: true, type: nil, name: nil, loads: nil, description: nil, comment: nil, ast_node: nil, default_value: NOT_CONFIGURED, as: nil, from_resolver: false, camelize: true, prepare: nil, owner:, validates: nil, directives: nil, deprecation_reason: nil, replace_null_with_default: false, &definition_block) ⇒ Argument
Parameters
arg_name(Symbol)type_exprdesc(String)type(Class, Array<Class>) — Input type; positional argument also acceptedname(Symbol) — positional argument also accepteddefinition_block(Proc) — Called with the newly-created Argumentowner(Class) — Private, used by GraphQL-Ruby during schema definitionrequired(Boolean, :nullable) — if true, this argument is non-null; if false, this argument is nullable. If:nullable, then the argument must be provided, though it may benull.description(String)default_value(Object)loads(Class, Array<Class>) — A GraphQL type to load for the given ID when one is presentas(Symbol) — Override the keyword name when passed to a methodprepare(Symbol) — A method to call to transform this argument's valuebefore sending it to field resolutioncamelize(Boolean) — if true, the name will be camelized when building the schemafrom_resolver(Boolean) — if true, a Resolver class defined this argumentdirectives(Hash{Class => Hash})deprecation_reason(String)validates(Hash, nil) — Options for building validators, if any should be appliedreplace_null_with_default(Boolean) — iftrue, incoming values ofnullwill be replaced with the configureddefault_valuecomment(String) — Private, used by GraphQL-Ruby when parsing GraphQL schema filesast_node(GraphQL::Language::Nodes::InputValueDefinition) — Private, used by GraphQL-Ruby when parsing schema files
:call-seq:
initialize(Symbol arg_name, type_expr, String desc, bool | :nullable required:, Class | Array[Class] type:, Symbol name:, Class | Array[Class] loads:, String description:, String comment:, GraphQL::Language::Nodes::InputValueDefinition ast_node:, Object default_value:, Symbol as:, bool from_resolver:, bool camelize:, Symbol prepare:, Class owner:, Hash | nil validates:, Hash[Class, Hash] directives:, String deprecation_reason:, bool replace_null_with_default:, Proc &definition_block)
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 |
# File 'lib/graphql/schema/argument.rb', line 260 def initialize(arg_name = nil, type_expr = nil, desc = nil, required: true, type: nil, name: nil, loads: nil, description: nil, comment: nil, ast_node: nil, default_value: NOT_CONFIGURED, as: nil, from_resolver: false, camelize: true, prepare: nil, owner:, validates: nil, directives: nil, deprecation_reason: nil, replace_null_with_default: false, &definition_block) arg_name ||= name @name = -(camelize ? Member::BuildType.camelize(arg_name.to_s) : arg_name.to_s) NameValidator.validate!(@name) @type_expr = type_expr || type @description = desc || description @comment = comment @null = required != true @default_value = default_value if replace_null_with_default if !default_value? raise ArgumentError, "`replace_null_with_default: true` requires a default value, please provide one with `default_value: ...`" end @replace_null_with_default = true end @owner = owner @as = as @loads = loads @keyword = as || (arg_name.is_a?(Symbol) ? arg_name : Schema::Member::BuildType.underscore(@name).to_sym) @prepare = prepare @ast_node = ast_node @from_resolver = from_resolver self.deprecation_reason = deprecation_reason if directives directives.each do |dir_class, | directive(dir_class, **) end end if validates && !validates.empty? self.validates(validates) end if required == :nullable self.owner.validates(required: { argument: @keyword }) end if definition_block # `self` will still be self, it will also be the first argument to the block: instance_exec(self, &definition_block) end end |
Instance Attribute Details
#comment(text = nil) ⇒ Object
Returns
String— Comment for this argument
:call-seq:
comment(text) -> String
364 365 366 367 368 369 370 |
# File 'lib/graphql/schema/argument.rb', line 364 def comment(text = nil) if text @comment = text else @comment end end |
#description(text = nil) ⇒ Object
Returns
String— Documentation for this argument
:call-seq:
description(text) -> String
348 349 350 351 352 353 354 |
# File 'lib/graphql/schema/argument.rb', line 348 def description(text = nil) if text @description = text else @description end end |
#keyword ⇒ Object (readonly)
Returns
Symbol— This argument's name in Ruby keyword arguments
217 218 219 |
# File 'lib/graphql/schema/argument.rb', line 217 def keyword @keyword end |
#loads ⇒ Object (readonly)
Returns
Class, Module, nil— If this argument should load an application object, this is the type of object to load
222 223 224 |
# File 'lib/graphql/schema/argument.rb', line 222 def loads @loads end |
#name ⇒ Object (readonly) Also known as: graphql_name
Returns
String— the GraphQL name for this argument, camelized unlesscamelize: falseis provided
189 190 191 |
# File 'lib/graphql/schema/argument.rb', line 189 def name @name end |
#owner ⇒ Object (readonly)
Returns
GraphQL::Schema::Field, Class— The field or input object this argument belongs to
195 196 197 |
# File 'lib/graphql/schema/argument.rb', line 195 def owner @owner end |
Instance Method Details
#authorized?(obj, value, ctx) ⇒ Boolean
399 400 401 |
# File 'lib/graphql/schema/argument.rb', line 399 def (obj, value, ctx) (obj, value, ctx, as_type: type) end |
#authorized_as_type?(obj, value, ctx, as_type:) ⇒ Boolean
403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 |
# File 'lib/graphql/schema/argument.rb', line 403 def (obj, value, ctx, as_type:) if value.nil? return true end if as_type.kind.non_null? as_type = as_type.of_type end if as_type.kind.list? value.each do |v| if !(obj, v, ctx, as_type: as_type.of_type) return false end end elsif as_type.kind.input_object? return as_type.(obj, value, ctx) end # None of the early-return conditions were activated, # so this is authorized. true end |
#authorizes?(context) ⇒ Boolean
395 396 397 |
# File 'lib/graphql/schema/argument.rb', line 395 def (context) self.method(:authorized?).owner != GraphQL::Schema::Argument || type.unwrap.(context) end |
#coerce_into_values(parent_object, values, context, argument_values) ⇒ Object
:nodoc:
492 493 494 495 496 497 498 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 548 549 550 551 |
# File 'lib/graphql/schema/argument.rb', line 492 def coerce_into_values(parent_object, values, context, argument_values) # :nodoc: arg_name = graphql_name arg_key = keyword default_used = false if values.key?(arg_name) value = values[arg_name] elsif values.key?(arg_key) value = values[arg_key] elsif default_value? value = default_value default_used = true else # no value at all owner.validate_directive_argument(self, nil) return end if value.nil? && replace_null_with_default? value = default_value default_used = true end loaded_value = nil #: untyped coerced_value = begin type.coerce_input(value, context) rescue StandardError => err handle_or_reraise_arg_error(context, err) end # If this isn't lazy, then the block returns eagerly and assigns the result here # If it _is_ lazy, then we write the lazy to the hash, then update it later argument_values[arg_key] = context.query.after_lazy(coerced_value) do |resolved_coerced_value| owner.validate_directive_argument(self, resolved_coerced_value) prepared_value = begin prepare_value(parent_object, resolved_coerced_value, context: context) rescue StandardError => err handle_or_reraise_arg_error(context, err) end if loads && !from_resolver? loaded_value = begin (owner, prepared_value, context) rescue StandardError => err handle_or_reraise_arg_error(context, err) end end maybe_loaded_value = loaded_value || prepared_value context.query.after_lazy(maybe_loaded_value) do |resolved_loaded_value| # TODO code smell to access such a deeply-nested constant in a distant module argument_values[arg_key] = GraphQL::Execution::Interpreter::ArgumentValue.new( value: resolved_loaded_value, original_value: resolved_coerced_value, definition: self, default_used: default_used, ) end end end |
#default_value(new_default_value = NOT_CONFIGURED) ⇒ Object
Parameters
default_value(Object) — The value to use when the client doesn't provide one
Returns
Object— the value used when the client doesn't provide a value for this argument
:call-seq:
default_value(new_default_value) -> Object
319 320 321 322 323 324 |
# File 'lib/graphql/schema/argument.rb', line 319 def default_value(new_default_value = NOT_CONFIGURED) if new_default_value != NOT_CONFIGURED @default_value = new_default_value end @default_value end |
#default_value? ⇒ Boolean
Returns
Boolean— True if this argument has a default value
:call-seq:
default_value?() -> bool
332 333 334 |
# File 'lib/graphql/schema/argument.rb', line 332 def default_value? @default_value != NOT_CONFIGURED end |
#deprecation_reason(text = nil) ⇒ Object
Returns
String— Deprecation reason for this argument
:call-seq:
deprecation_reason(text) -> String
378 379 380 381 382 383 384 |
# File 'lib/graphql/schema/argument.rb', line 378 def deprecation_reason(text = nil) if text self.deprecation_reason = text else super() end end |
#deprecation_reason=(new_reason) ⇒ Object
386 387 388 389 |
# File 'lib/graphql/schema/argument.rb', line 386 def deprecation_reason=(new_reason) validate_deprecated_or_optional(null: @null, deprecation_reason: new_reason) super end |
#freeze ⇒ Object
454 455 456 457 |
# File 'lib/graphql/schema/argument.rb', line 454 def freeze statically_coercible? super end |
#from_resolver? ⇒ Boolean
Returns
Boolean— true if a resolver defined this argument
:call-seq:
from_resolver?() -> bool
230 231 232 |
# File 'lib/graphql/schema/argument.rb', line 230 def from_resolver? @from_resolver end |
#handle_or_reraise_arg_error(context, err) ⇒ Object
When a rescue_from handler returns an error object instead of raising,
it must not be used as this argument's value — raise it so that
coerce_arguments short-circuits resolution with it.
556 557 558 559 560 561 562 |
# File 'lib/graphql/schema/argument.rb', line 556 def handle_or_reraise_arg_error(context, err) # :nodoc: handled_err = context.schema.handle_or_reraise(context, err) if handled_err.is_a?(GraphQL::ExecutionError) || handled_err.is_a?(GraphQL::UnauthorizedError) raise handled_err end handled_err end |
#inspect ⇒ Object
305 306 307 |
# File 'lib/graphql/schema/argument.rb', line 305 def inspect "#<#{self.class} #{path}: #{type.to_type_signature}#{description ? " @description=#{description.inspect}" : ""}>" end |
#load_and_authorize_value(load_method_owner, coerced_value, context) ⇒ Object
564 565 566 567 568 569 570 571 572 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 |
# File 'lib/graphql/schema/argument.rb', line 564 def (load_method_owner, coerced_value, context) if coerced_value.nil? return nil end arg_load_method = "load_#{keyword}" if load_method_owner.respond_to?(arg_load_method) custom_loaded_value = if load_method_owner.is_a?(Class) load_method_owner.public_send(arg_load_method, coerced_value, context) else load_method_owner.public_send(arg_load_method, coerced_value) end context.query.after_lazy(custom_loaded_value) do |custom_value| if loads if type.list? loaded_values = [] context.dataloader.run_isolated do custom_value.each_with_index.map { |custom_val, idx| id = coerced_value[idx] context.dataloader.append_job do loaded_values[idx] = load_method_owner.(self, id, context, custom_val) end } end context.schema.after_any_lazies(loaded_values, &:itself) else load_method_owner.(self, coerced_value, context, custom_loaded_value) end else custom_value end end elsif loads if type.list? loaded_values = [] # We want to run these list items all together, # but we also need to wait for the result so we can return it :S context.dataloader.run_isolated do coerced_value.each_with_index { |val, idx| context.dataloader.append_job do loaded_values[idx] = load_method_owner.(self, val, context) end } end context.schema.after_any_lazies(loaded_values, &:itself) else load_method_owner.(self, coerced_value, context) end else coerced_value end end |
#prepare(new_prepare = NOT_CONFIGURED) ⇒ Object
Parameters
new_prepare(Method, Proc)
Returns
Symbol— A method or proc to call to transform this value before sending it to field resolution method
:call-seq:
prepare(Method | Proc new_prepare) -> Symbol
207 208 209 210 211 212 |
# File 'lib/graphql/schema/argument.rb', line 207 def prepare(new_prepare = NOT_CONFIGURED) if new_prepare != NOT_CONFIGURED @prepare = new_prepare end @prepare end |
#prepare_value(obj, value, context: nil) ⇒ Object
Apply the prepare configuration to value, using methods from obj.
Used by the runtime.
461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 |
# File 'lib/graphql/schema/argument.rb', line 461 def prepare_value(obj, value, context: nil) # :nodoc: if type.unwrap.kind.input_object? value = recursively_prepare_input_object(value, type, context) end Schema::Validator.validate!(validators, obj, context, value) if @prepare.nil? value elsif @prepare.is_a?(String) || @prepare.is_a?(Symbol) if obj.nil? # The problem here is, we _used to_ prepare while building variables. # But now we don't have the runtime object there. # # This will have to be called later, when the runtime object _is_ available. value elsif obj.respond_to?(@prepare) obj.public_send(@prepare, value) elsif owner.respond_to?(@prepare) owner.public_send(@prepare, value, context || obj.context) else raise "Invalid prepare for #{@owner.name}.name: #{@prepare.inspect}. "\ "Could not find prepare method #{@prepare} on #{obj.class} or #{owner}." end elsif @prepare.respond_to?(:call) @prepare.call(value, context || obj.context) else raise "Invalid prepare for #{@owner.name}.name: #{@prepare.inspect}" end end |
#replace_null_with_default? ⇒ Boolean
336 337 338 |
# File 'lib/graphql/schema/argument.rb', line 336 def replace_null_with_default? @replace_null_with_default end |
#statically_coercible? ⇒ Boolean
448 449 450 451 452 |
# File 'lib/graphql/schema/argument.rb', line 448 def statically_coercible? return @statically_coercible if defined?(@statically_coercible) requires_parent_object = @prepare.is_a?(String) || @prepare.is_a?(Symbol) || @own_validators @statically_coercible = !requires_parent_object end |
#type ⇒ Object
436 437 438 439 440 441 442 443 444 445 446 |
# File 'lib/graphql/schema/argument.rb', line 436 def type @type ||= begin parsed_type = begin Member::BuildType.parse_type(@type_expr, null: @null) rescue StandardError => err raise ArgumentError, "Couldn't build type for Argument #{@owner.name}.#{name}: #{err.class.name}: #{err.}", err.backtrace end # Use the setter method to get validations self.type = parsed_type end end |
#type=(new_type) ⇒ Object
426 427 428 429 430 431 432 433 434 |
# File 'lib/graphql/schema/argument.rb', line 426 def type=(new_type) validate_input_type(new_type) # This isn't true for LateBoundTypes, but we can assume those will # be updated via this codepath later in schema setup. if new_type.respond_to?(:non_null?) validate_deprecated_or_optional(null: !new_type.non_null?, deprecation_reason: deprecation_reason) end @type = new_type end |
#validate_default_value ⇒ Object
:nodoc:
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 |
# File 'lib/graphql/schema/argument.rb', line 616 def validate_default_value # :nodoc: return unless default_value? coerced_default_value = begin # This is weird, but we should accept single-item default values for list-type arguments. # If we used `coerce_isolated_input` below, it would do this for us, but it's not really # the right thing here because we expect default values in application format (Ruby values) # not GraphQL format (scalar values). # # But I don't think Schema::List#coerce_result should apply wrapping to single-item lists. prepped_default_value = if default_value.nil? nil elsif (type.kind.list? || (type.kind.non_null? && type.of_type.list?)) && !default_value.respond_to?(:map) [default_value] else default_value end type.coerce_isolated_result(prepped_default_value) unless prepped_default_value.nil? rescue GraphQL::Schema::Enum::UnresolvedValueError # It raises this, which is helpful at runtime, but not here... default_value end res = type.valid_isolated_input?(coerced_default_value) if !res raise InvalidDefaultValueError.new(self) end end |
#visible?(context) ⇒ Boolean
391 392 393 |
# File 'lib/graphql/schema/argument.rb', line 391 def visible?(context) true end |