Class: GraphQL::Schema

Inherits:
Object
  • Object
show all
Extended by:
Autoload, EmptyObjects, FindInheritedValue, Member::HasAstNode
Defined in:
lib/graphql/schema.rb,
lib/graphql/schema/enum.rb,
lib/graphql/schema/list.rb,
lib/graphql/schema/field.rb,
lib/graphql/schema/union.rb,
lib/graphql/schema/finder.rb,
lib/graphql/schema/loader.rb,
lib/graphql/schema/member.rb,
lib/graphql/schema/object.rb,
lib/graphql/schema/scalar.rb,
lib/graphql/schema/warden.rb,
lib/graphql/schema/printer.rb,
lib/graphql/schema/timeout.rb,
lib/graphql/schema/wrapper.rb,
lib/graphql/schema/addition.rb,
lib/graphql/schema/argument.rb,
lib/graphql/schema/mutation.rb,
lib/graphql/schema/non_null.rb,
lib/graphql/schema/resolver.rb,
lib/graphql/schema/directive.rb,
lib/graphql/schema/interface.rb,
lib/graphql/schema/validator.rb,
lib/graphql/schema/enum_value.rb,
lib/graphql/schema/visibility.rb,
lib/graphql/schema/input_object.rb,
lib/graphql/schema/subscription.rb,
lib/graphql/schema/member/scoped.rb,
lib/graphql/schema/always_visible.rb,
lib/graphql/schema/built_in_types.rb,
lib/graphql/schema/directive/skip.rb,
lib/graphql/schema/base_64_encoder.rb,
lib/graphql/schema/field_extension.rb,
lib/graphql/schema/late_bound_type.rb,
lib/graphql/schema/member/has_path.rb,
lib/graphql/schema/type_expression.rb,
lib/graphql/schema/type_membership.rb,
lib/graphql/schema/directive/one_of.rb,
lib/graphql/schema/ractor_shareable.rb,
lib/graphql/schema/visibility/visit.rb,
lib/graphql/schema/directive/feature.rb,
lib/graphql/schema/directive/flagged.rb,
lib/graphql/schema/directive/include.rb,
lib/graphql/schema/member/build_type.rb,
lib/graphql/schema/member/has_fields.rb,
lib/graphql/schema/unique_within_type.rb,
lib/graphql/schema/visibility/profile.rb,
lib/graphql/schema/directive/transform.rb,
lib/graphql/schema/member/has_ast_node.rb,
lib/graphql/schema/directive/deprecated.rb,
lib/graphql/schema/find_inherited_value.rb,
lib/graphql/schema/introspection_system.rb,
lib/graphql/schema/member/has_arguments.rb,
lib/graphql/schema/visibility/migration.rb,
lib/graphql/schema/build_from_definition.rb,
lib/graphql/schema/field/scope_extension.rb,
lib/graphql/schema/member/has_dataloader.rb,
lib/graphql/schema/member/has_directives.rb,
lib/graphql/schema/member/has_interfaces.rb,
lib/graphql/schema/member/has_validators.rb,
lib/graphql/schema/directive/specified_by.rb,
lib/graphql/schema/member/relay_shortcuts.rb,
lib/graphql/schema/member/validates_input.rb,
lib/graphql/schema/relay_classic_mutation.rb,
lib/graphql/schema/member/base_dsl_methods.rb,
lib/graphql/schema/validator/all_validator.rb,
lib/graphql/schema/member/has_authorization.rb,
lib/graphql/schema/has_single_input_argument.rb,
lib/graphql/schema/member/graphql_type_names.rb,
lib/graphql/schema/resolver/has_payload_type.rb,
lib/graphql/schema/field/connection_extension.rb,
lib/graphql/schema/member/type_system_helpers.rb,
lib/graphql/schema/validator/format_validator.rb,
lib/graphql/schema/validator/length_validator.rb,
lib/graphql/schema/validator/required_validator.rb,
lib/graphql/schema/member/has_deprecation_reason.rb,
lib/graphql/schema/validator/exclusion_validator.rb,
lib/graphql/schema/validator/inclusion_validator.rb,
lib/graphql/schema/validator/allow_null_validator.rb,
lib/graphql/schema/validator/allow_blank_validator.rb,
lib/graphql/schema/member/has_unresolved_type_error.rb,
lib/graphql/schema/validator/numericality_validator.rb,
lib/graphql/schema/build_from_definition/resolve_map.rb,
lib/graphql/schema/build_from_definition/resolve_map/default_resolve.rb

Overview

A GraphQL schema which may be queried with GraphQL::Query.

The Schema contains:

  • types for exposing your application
  • query analyzers for assessing incoming queries (including max depth & max complexity restrictions)
  • execution strategies for running incoming queries

Schemas start with root types, Schema.query, Schema.mutation and Schema.subscription. The schema will traverse the tree of fields & types, using those as starting points. Any undiscoverable types may be provided with the types configuration.

Schemas can restrict large incoming queries with max_depth and max_complexity configurations. (These configurations can be overridden by specific calls to Schema.execute)

Schema configuration reference

  • Root types are registered with query, mutation, and subscription; use orphan_types for interface-only object types.
  • object_from_id, id_from_object, and resolve_type implement Relay object identification and abstract-type resolution.
  • type_error, rescue_from, parse_error, and query_stack_error provide execution error hooks.
  • max_depth, max_complexity, validate_timeout, validate_max_errors, and max_query_string_tokens limit incoming work.
  • extra_types, introspection, trace_with, analyzers, context_class, query_class, lazy_resolve, and use configure execution.

The schema definition guide contains setup examples and links each contract above to its API method. Keep method-specific behavior in the comments for those methods so this page remains the source of truth.

Root Types

query, mutation, and subscription register the entry-point object types for a schema. Each may receive a type class or a block for lazy loading:

query Types::Query
mutation { Types::Mutation }
subscription { Types::Subscription }

Use Schema.orphan_types for object types which implement an interface but aren't reachable from a field return type. Use Schema.extra_types when a type should be printed and included in introspection without being connected to the schema's type graph.

Object Identification

Relay-style node(id:) fields, arguments configured with loads:, and the ObjectCache use Schema.object_from_id to fetch an application object. Return nil when the object does not exist or is not visible to the current operation. Implement Schema.id_from_object to produce a stable ID which can be passed back to object_from_id.

Schema.resolve_type maps an application object to its runtime GraphQL type when a field returns an interface or union.

Error Handling

Override Schema.type_error to handle mismatches between application values and the GraphQL type system. Register application exception handlers with Schema.rescue_from. Schema.parse_error handles invalid query strings, and Schema.query_stack_error is called when execution encounters a SystemStackError.

Default Limits

Schema.max_depth limits nested field selections and Schema.max_complexity limits the calculated cost of a query. Schema.default_max_page_size limits connection fields. Schema.validate_timeout, Schema.validate_max_errors, and Schema.max_query_string_tokens bound validation and parsing work. These limits can be configured on a schema and, where documented, overridden for an individual execution.

Introspection

Schema.extra_types adds otherwise unreachable types to printed SDL and introspection results. Pass a custom namespace to Schema.introspection to replace or extend the default introspection system.

Authorization

Schema.unauthorized_object and Schema.unauthorized_field run when an authorization hook returns false. Return a replacement value or raise GraphQL::ExecutionError to add a client-facing error.

Execution Configuration

Schema.trace_with installs tracing modules. Schema.query_analyzer and Schema.multiplex_analyzer register analysis hooks. Schema.default_logger configures runtime logging, while Schema.context_class and Schema.query_class select the classes used during execution. Schema.lazy_resolve registers promise-like values, and Schema.use installs schema plugins such as Dataloader and Visibility.

Examples

Example: defining a schema

class MySchema < GraphQL::Schema
  query QueryType
  # If types are only connected by way of interfaces, they must be added here
  orphan_types ImageType, AudioType
end

Direct Known Subclasses

Query::NullContext::NullSchema

Defined Under Namespace

Modules: AlwaysVisible, Base64Encoder, BuildFromDefinition, DefaultTraceClass, FindInheritedValue, HasSingleInputArgument, Interface, Loader, RactorShareable, ResolveTypeWithType, SubclassGetReferencesTo, TypeExpression, UniqueWithinType Classes: Addition, Argument, Directive, DuplicateNamesError, Enum, EnumValue, Field, FieldExtension, Finder, InputObject, IntrospectionSystem, InvalidDocumentError, LateBoundType, List, Member, Mutation, NonNull, Object, Printer, RelayClassicMutation, Resolver, Scalar, Subscription, Timeout, TypeMembership, Union, UnresolvedLateBoundTypeError, Validator, Visibility, Warden, Wrapper

Constant Summary collapse

BUILT_IN_TYPES =
{
  "Int" => GraphQL::Types::Int,
  "String" => GraphQL::Types::String,
  "Float" => GraphQL::Types::Float,
  "Boolean" => GraphQL::Types::Boolean,
  "ID" => GraphQL::Types::ID,
}

Constants included from EmptyObjects

EmptyObjects::EMPTY_ARRAY, EmptyObjects::EMPTY_HASH

Class Attribute Summary collapse

Attributes included from Member::HasAstNode

#ast_node

Class Method Summary collapse

Methods included from Member::HasAstNode

extended, inherited

Methods included from FindInheritedValue

extended, included

Methods included from Autoload

autoload, eager_load!

Class Attribute Details

.analysis_engine ⇒ Object



1204
1205
1206
# File 'lib/graphql/schema.rb', line 1204

def analysis_engine
  @analysis_engine || find_inherited_value(:analysis_engine, self.default_analysis_engine)
end

.connections ⇒ Object

Returns

  • GraphQL::Pagination::Connections — if installed

:call-seq:

connections() -> GraphQL::Pagination::Connections


632
633
634
635
636
637
638
639
640
641
642
643
644
645
# File 'lib/graphql/schema.rb', line 632

def connections
  if defined?(@connections)
    @connections
  else
    inherited_connections = find_inherited_value(:connections, nil)
    # This schema is part of an inheritance chain which is using new connections,
    # make a new instance, so we don't pollute the upstream one.
    if inherited_connections
      @connections = Pagination::Connections.new(schema: self)
    else
      nil
    end
  end
end

.dataloader_class ⇒ Object



932
933
934
# File 'lib/graphql/schema.rb', line 932

def dataloader_class # :nodoc:
  @dataloader_class || GraphQL::Dataloader::NullDataloader
end

.detailed_trace ⇒ Object

Returns

  • GraphQL::Tracing::DetailedTrace — if it has been configured for this schema


1850
1851
1852
# File 'lib/graphql/schema.rb', line 1850

def detailed_trace
  @detailed_trace
end

.error_bubbling(new_error_bubbling = nil) ⇒ Object



1208
1209
1210
1211
1212
1213
1214
1215
# File 'lib/graphql/schema.rb', line 1208

def error_bubbling(new_error_bubbling = nil)
  if !new_error_bubbling.nil?
    warn("error_bubbling(#{new_error_bubbling.inspect}) is deprecated; the default value of `false` will be the only option in GraphQL-Ruby 3.0")
    @error_bubbling = new_error_bubbling
  else
    @error_bubbling.nil? ? find_inherited_value(:error_bubbling) : @error_bubbling
  end
end

.max_complexity(max_complexity = nil, count_introspection_fields: true) ⇒ Object



1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
# File 'lib/graphql/schema.rb', line 1183

def max_complexity(max_complexity = nil, count_introspection_fields: true)
  if max_complexity
    @max_complexity = max_complexity
    @max_complexity_count_introspection_fields = count_introspection_fields
  elsif defined?(@max_complexity)
    @max_complexity
  else
    find_inherited_value(:max_complexity)
  end
end

.max_depth(new_max_depth = nil, count_introspection_fields: true) ⇒ Object



1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
# File 'lib/graphql/schema.rb', line 1221

def max_depth(new_max_depth = nil, count_introspection_fields: true)
  if new_max_depth
    @max_depth = new_max_depth
    @count_introspection_fields = count_introspection_fields
  elsif defined?(@max_depth)
    @max_depth
  else
    find_inherited_value(:max_depth)
  end
end

.null_context ⇒ Object



521
522
523
# File 'lib/graphql/schema.rb', line 521

def null_context
  @null_context || GraphQL::Query::NullContext.instance
end

.use_visibility_profile=(value) ⇒ Object (writeonly)

:nodoc:



855
856
857
# File 'lib/graphql/schema.rb', line 855

def use_visibility_profile=(value)
  @use_visibility_profile = value
end

.using_backtrace ⇒ Object

:nodoc:



1486
1487
1488
# File 'lib/graphql/schema.rb', line 1486

def using_backtrace
  @using_backtrace
end

.validate_max_errors(new_validate_max_errors = NOT_CONFIGURED) ⇒ Object



1173
1174
1175
1176
1177
1178
1179
# File 'lib/graphql/schema.rb', line 1173

def validate_max_errors(new_validate_max_errors = NOT_CONFIGURED)
  if NOT_CONFIGURED.equal?(new_validate_max_errors)
    defined?(@validate_max_errors) ? @validate_max_errors : find_inherited_value(:validate_max_errors)
  else
    @validate_max_errors = new_validate_max_errors
  end
end

.validate_timeout(new_validate_timeout = NOT_CONFIGURED) ⇒ Object



1121
1122
1123
1124
1125
1126
1127
1128
1129
# File 'lib/graphql/schema.rb', line 1121

def validate_timeout(new_validate_timeout = NOT_CONFIGURED)
  if !NOT_CONFIGURED.equal?(new_validate_timeout)
    @validate_timeout = new_validate_timeout
  elsif defined?(@validate_timeout)
    @validate_timeout
  else
    find_inherited_value(:validate_timeout) || 3
  end
end

.visibility ⇒ Object

:nodoc:



856
857
858
# File 'lib/graphql/schema.rb', line 856

def visibility
  @visibility
end

.visibility_profile_class ⇒ Object

:nodoc:



845
846
847
848
849
850
851
852
853
# File 'lib/graphql/schema.rb', line 845

def visibility_profile_class # :nodoc:
  if defined?(@visibility_profile_class)
    @visibility_profile_class
  elsif superclass.respond_to?(:visibility_profile_class)
    superclass.visibility_profile_class
  else
    GraphQL::Schema::Visibility::Profile
  end
end

.warden_class ⇒ Object

:nodoc:



833
834
835
836
837
838
839
840
841
# File 'lib/graphql/schema.rb', line 833

def warden_class # :nodoc:
  if defined?(@warden_class)
    @warden_class
  elsif superclass.respond_to?(:warden_class)
    superclass.warden_class
  else
    GraphQL::Schema::Warden
  end
end

Class Method Details

.add_subscription_extension_if_necessary ⇒ Object

:nodoc:



2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
# File 'lib/graphql/schema.rb', line 2171

def add_subscription_extension_if_necessary # :nodoc:
  # TODO: when there's a proper API for extending root types, migrat this to use it.
  if !defined?(@subscription_extension_added) && @subscription_object.is_a?(Class) && self.subscriptions
    @subscription_extension_added = true
    subscription.all_field_definitions.each do |field|
      if !field.extensions.any? { |ext| ext.is_a?(Subscriptions::DefaultSubscriptionResolveExtension) }
        field.extension(Subscriptions::DefaultSubscriptionResolveExtension)
      end
    end
  end
end

.after_any_lazies(maybe_lazies) ⇒ Object

Return a lazy if any of maybe_lazies are lazy, otherwise, call the block eagerly and return the result.

Parameters

  • maybe_lazies (Array)


2261
2262
2263
2264
2265
2266
2267
2268
2269
# File 'lib/graphql/schema.rb', line 2261

def after_any_lazies(maybe_lazies) # :nodoc:
  if maybe_lazies.any? { |l| lazy?(l) }
    GraphQL::Execution::Lazy.all(maybe_lazies).then do |result|
      yield result
    end
  else
    yield maybe_lazies
  end
end

.after_lazy(value, &block) ⇒ Object

Call the given block at the right time, either:

  • Right away, if value is not registered with lazy_resolve
  • After resolving value, if it's registered with lazy_resolve (eg, Promise)


2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
# File 'lib/graphql/schema.rb', line 2204

def after_lazy(value, &block) # :nodoc:
  if lazy?(value)
    GraphQL::Execution::Lazy.new do
      result = sync_lazy(value)
      # The returned result might also be lazy, so check it, too
      after_lazy(result, &block)
    end
  else
    yield(value) if block_given?
  end
end

.allow_legacy_invalid_empty_selections_on_union(new_value = NOT_CONFIGURED) ⇒ Object

This setting controls how GraphQL-Ruby handles empty selections on Union types.

To opt into future, spec-compliant behavior where these selections are rejected, set this to false.

If you need to support previous, non-spec behavior which allowed selecting union fields but not selecting any fields on that union, set this to true to continue allowing that behavior.

If this is true, then .legacy_invalid_empty_selections_on_union_with_type will be called with Query objects with that kind of selections. You must implement that method

Parameters

  • new_value (Boolean)

Returns

  • true, false, nil

:call-seq:

allow_legacy_invalid_empty_selections_on_union(bool new_value) -> true | false | nil


2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
# File 'lib/graphql/schema.rb', line 2306

def allow_legacy_invalid_empty_selections_on_union(new_value = NOT_CONFIGURED)
  if NOT_CONFIGURED.equal?(new_value)
    if defined?(@allow_legacy_invalid_empty_selections_on_union)
      @allow_legacy_invalid_empty_selections_on_union
    else
      find_inherited_value(:allow_legacy_invalid_empty_selections_on_union)
    end
  else
    @allow_legacy_invalid_empty_selections_on_union = new_value
  end
end

.allow_legacy_invalid_field_conflicts(new_value = NOT_CONFIGURED) ⇒ Object

This setting controls how GraphQL-Ruby handles fields with the same response name but different names or arguments, when previous versions of GraphQL-Ruby treated them as mutually exclusive, but the GraphQL spec doesn't. The spec treats fields as mutually exclusive only when their parent types are different object types. For example:

  • ... on Product { ...ProductFields options(first: 2) { id } }, when ProductFields also selects options on Product
  • ... on Feline { volume: meowVolume } and ... on Canine { volume: barkVolume }, when Feline and Canine are interfaces

When set to false, GraphQL-Ruby will reject those queries with a validation error (as per the GraphQL spec).

When set to true, GraphQL-Ruby will call .legacy_invalid_field_conflicts when the scenario is encountered.

When not configured, GraphQL-Ruby allows those queries and logs a warning.

Parameters

  • new_value (Boolean) — true permits the legacy behavior, false rejects it.

Returns

  • true, false, nil

:call-seq:

allow_legacy_invalid_field_conflicts(bool new_value) -> true | false | nil


2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
# File 'lib/graphql/schema.rb', line 2507

def allow_legacy_invalid_field_conflicts(new_value = NOT_CONFIGURED)
  if NOT_CONFIGURED.equal?(new_value)
    if defined?(@allow_legacy_invalid_field_conflicts)
      @allow_legacy_invalid_field_conflicts
    else
      find_inherited_value(:allow_legacy_invalid_field_conflicts)
    end
  else
    @allow_legacy_invalid_field_conflicts = new_value
  end
end

.allow_legacy_invalid_return_type_conflicts(new_value = NOT_CONFIGURED) ⇒ Object

This setting controls how GraphQL-Ruby handles overlapping selections on scalar types when the types don't match.

When set to false, GraphQL-Ruby will reject those queries with a validation error (as per the GraphQL spec).

When set to true, GraphQL-Ruby will call .legacy_invalid_return_type_conflicts when the scenario is encountered.

Parameters

  • new_value (Boolean) — true permits the legacy behavior, false rejects it.

Returns

  • true, false, nil

:call-seq:

allow_legacy_invalid_return_type_conflicts(bool new_value) -> true | false | nil


2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
# File 'lib/graphql/schema.rb', line 2444

def allow_legacy_invalid_return_type_conflicts(new_value = NOT_CONFIGURED)
  if NOT_CONFIGURED.equal?(new_value)
    if defined?(@allow_legacy_invalid_return_type_conflicts)
      @allow_legacy_invalid_return_type_conflicts
    else
      find_inherited_value(:allow_legacy_invalid_return_type_conflicts)
    end
  else
    @allow_legacy_invalid_return_type_conflicts = new_value
  end
end

.allow_legacy_invalid_variable_usages(new_value = NOT_CONFIGURED) ⇒ Object

This setting controls how GraphQL-Ruby handles variable usages which the GraphQL spec doesn't allow, but which previous versions of GraphQL-Ruby didn't reject:

  • A variable in a fragment, when the fragment comes before the operation, or when another operation uses the fragment
  • A nullable variable with a = null default value, in a non-null position
  • A variable in a nested list value, for example [[$var]]

When set to false, GraphQL-Ruby will reject those queries with a validation error (as per the GraphQL spec).

When set to true, GraphQL-Ruby will call .legacy_invalid_variable_usages when the scenario is encountered.

When not configured, GraphQL-Ruby allows those queries and logs a warning.

Parameters

  • new_value (Boolean) — true permits the legacy behavior, false rejects it.

Returns

  • true, false, nil

:call-seq:

allow_legacy_invalid_variable_usages(bool new_value) -> true | false | nil


2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
# File 'lib/graphql/schema.rb', line 2390

def allow_legacy_invalid_variable_usages(new_value = NOT_CONFIGURED)
  if NOT_CONFIGURED.equal?(new_value)
    if defined?(@allow_legacy_invalid_variable_usages)
      @allow_legacy_invalid_variable_usages
    else
      find_inherited_value(:allow_legacy_invalid_variable_usages)
    end
  else
    @allow_legacy_invalid_variable_usages = new_value
  end
end

.as_json(context: {}, include_deprecated_args: true, include_schema_description: false, include_is_repeatable: false, include_specified_by_url: false, include_is_one_of: false) ⇒ Object

Return the Hash response of Introspection::INTROSPECTION_QUERY.

Parameters

  • context (Hash)
  • include_deprecated_args (Boolean) — If true, deprecated arguments will be included in the JSON response
  • include_schema_description (Boolean) — If true, the schema's description will be queried and included in the response
  • include_is_repeatable (Boolean) — If true, isRepeatable: true|false will be included with the schema's directives
  • include_specified_by_url (Boolean) — If true, scalar types' specifiedByUrl: will be included in the response
  • include_is_one_of (Boolean) — If true, isOneOf: true|false will be included with input objects

Returns

  • Hash — GraphQL result

:call-seq:

as_json(Hash context:, bool include_deprecated_args:, bool include_schema_description:, bool include_is_repeatable:, bool include_specified_by_url:, bool include_is_one_of:) -> Hash


426
427
428
429
430
431
432
433
434
435
436
# File 'lib/graphql/schema.rb', line 426

def as_json(context: {}, include_deprecated_args: true, include_schema_description: false, include_is_repeatable: false, include_specified_by_url: false, include_is_one_of: false)
  introspection_query = Introspection.query(
    include_deprecated_args: include_deprecated_args,
    include_schema_description: include_schema_description,
    include_is_repeatable: include_is_repeatable,
    include_is_one_of: include_is_one_of,
    include_specified_by_url: include_specified_by_url,
  )

  execute(introspection_query, context: context).to_h
end

.build_trace_mode(mode) ⇒ Object



349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
# File 'lib/graphql/schema.rb', line 349

def build_trace_mode(mode)
  case mode
  when :default
    # Use the superclass's default mode if it has one, or else start an inheritance chain at the built-in base class.
    base_class = (superclass.respond_to?(:trace_class_for) && superclass.trace_class_for(mode, build: true)) || GraphQL::Tracing::Trace
    const_set(:DefaultTrace, Class.new(base_class) do
      include DefaultTraceClass
    end)
  else
    # First, see if the superclass has a custom-defined class for this.
    # Then, if it doesn't, use this class's default trace
    base_class = (superclass.respond_to?(:trace_class_for) && superclass.trace_class_for(mode)) || trace_class_for(:default, build: true)
    # Prepare the default trace class if it hasn't been initialized yet
    base_class ||= (own_trace_modes[:default] = build_trace_mode(:default))
    mods = trace_modules_for(mode)
    if base_class < DefaultTraceClass
      mods = trace_modules_for(:default) + mods
    end
    # Copy the existing default options into this mode's options
    default_options = trace_options_for(:default)
    add_trace_options_for(mode, default_options)

    Class.new(base_class) do
      !mods.empty? && include(*mods)
    end
  end
end

.complexity_cost_calculation_mode(new_mode = NOT_CONFIGURED) ⇒ Object

The legacy complexity implementation included several bugs:

  • In some cases, it used the lexically last field to determine a cost, instead of calculating the maximum among selections
  • In some cases, it called field complexity hooks repeatedly (when it should have only called them once)

The future implementation may produce higher total complexity scores, so it's not active by default yet. You can opt into the future default behavior by configuring :future here. Or, you can choose a mode for each query with .complexity_cost_calculation_mode_for.

The legacy mode is currently maintained alongside the future one, but it will be removed in a future GraphQL-Ruby version.

If you choose :compare, you must also implement .legacy_complexity_cost_calculation_mismatch to handle the input somehow.

Examples

Example: Opting into the future calculation mode

complexity_cost_calculation_mode(:future)

Example: Choosing the legacy mode (which will work until that mode is removed...)

complexity_cost_calculation_mode(:legacy)

Example: Run both modes for every query, call .legacy_complexity_cost_calculation_mismatch when they don't match:

complexity_cost_calculation_mode(:compare)


2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
# File 'lib/graphql/schema.rb', line 2575

def complexity_cost_calculation_mode(new_mode = NOT_CONFIGURED)
  if NOT_CONFIGURED.equal?(new_mode)
    if defined?(@complexity_cost_calculation_mode)
      @complexity_cost_calculation_mode
    else
      find_inherited_value(:complexity_cost_calculation_mode)
    end
  else
    @complexity_cost_calculation_mode = new_mode
  end
end

.complexity_cost_calculation_mode_for(multiplex_context) ⇒ Object

Implement this method to produce a per-query complexity cost calculation mode. (Technically, it's per-multiplex.)

This is a way to check the compatibility of queries coming to your API without adding overhead of running :compare for every query. You could sample traffic, turn it off/on with feature flags, or anything else.

Examples

Example: Sampling traffic

def self.complexity_cost_calculation_mode_for(_context)
  if rand < 0.1 # 10% of the time
    :compare
  else
    :legacy
  end
end

Example: Using a feature flag to manage future mode

def complexity_cost_calculation_mode_for(context)
  current_user = context[:current_user]
  if Flipper.enabled?(:future_complexity_cost, current_user)
    :future
  elsif rand < 0.5 # 50%
    :compare
  else
    :legacy
  end
end

Parameters

  • multiplex_context (Hash) — The context for the currently-running Execution::Multiplex (which contains one or more queries)

Returns

  • :future — Use the new calculation algorithm -- may be higher than :legacy
  • :legacy — Use the legacy calculation algorithm, warts and all
  • :compare — Run both algorithms and call .legacy_complexity_cost_calculation_mismatch if they don't match

:call-seq:

complexity_cost_calculation_mode_for(Hash multiplex_context) -> :future | :legacy | :compare


2633
2634
2635
# File 'lib/graphql/schema.rb', line 2633

def complexity_cost_calculation_mode_for(multiplex_context)
  complexity_cost_calculation_mode
end

.context_class(new_context_class = nil) ⇒ Object

Parameters

  • new_context_class (Class<GraphQL::Query::Context>) — A subclass to use when executing queries

:call-seq:

context_class(Class[GraphQL::Query::Context] new_context_class)


1425
1426
1427
1428
1429
1430
1431
# File 'lib/graphql/schema.rb', line 1425

def context_class(new_context_class = nil)
  if new_context_class
    @context_class = new_context_class
  else
    @context_class || find_inherited_value(:context_class, GraphQL::Query::Context)
  end
end

.count_introspection_fields ⇒ Object



1232
1233
1234
1235
1236
1237
1238
# File 'lib/graphql/schema.rb', line 1232

def count_introspection_fields
  if defined?(@count_introspection_fields)
    @count_introspection_fields
  else
    find_inherited_value(:count_introspection_fields, true)
  end
end

.cursor_encoder(new_encoder = nil) ⇒ Object



1043
1044
1045
1046
1047
1048
# File 'lib/graphql/schema.rb', line 1043

def cursor_encoder(new_encoder = nil)
  if new_encoder
    @cursor_encoder = new_encoder
  end
  @cursor_encoder || find_inherited_value(:cursor_encoder, Base64Encoder)
end

.default_analysis_engine ⇒ Object



1364
1365
1366
1367
1368
1369
1370
# File 'lib/graphql/schema.rb', line 1364

def default_analysis_engine
  if superclass <= GraphQL::Schema
    superclass.default_analysis_engine
  else
    @default_analysis_engine ||= GraphQL::Analysis::AST
  end
end

.default_directives ⇒ Object



1837
1838
1839
1840
1841
1842
1843
1844
1845
# File 'lib/graphql/schema.rb', line 1837

def default_directives
  @default_directives ||= {
    "include" => GraphQL::Schema::Directive::Include,
    "skip" => GraphQL::Schema::Directive::Skip,
    "deprecated" => GraphQL::Schema::Directive::Deprecated,
    "oneOf" => GraphQL::Schema::Directive::OneOf,
    "specifiedBy" => GraphQL::Schema::Directive::SpecifiedBy,
  }.freeze
end

.default_execution_next(new_value = NOT_CONFIGURED) ⇒ Object



2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
# File 'lib/graphql/schema.rb', line 2152

def default_execution_next(new_value = NOT_CONFIGURED)
  if !NOT_CONFIGURED.equal?(new_value)
    @default_execution_next = new_value
  elsif instance_variable_defined?(:@default_execution_next)
    @default_execution_next
  elsif superclass.respond_to?(:default_execution_next)
    superclass.default_execution_next
  else
    false
  end
end

.default_execution_strategy ⇒ Object



1356
1357
1358
1359
1360
1361
1362
# File 'lib/graphql/schema.rb', line 1356

def default_execution_strategy
  if superclass <= GraphQL::Schema
    superclass.default_execution_strategy
  else
    @default_execution_strategy ||= GraphQL::Execution::Interpreter
  end
end

.default_logger(new_default_logger = NOT_CONFIGURED) ⇒ Object

Parameters

  • new_default_logger (#log) — Something to use for logging messages

:call-seq:

default_logger(#log new_default_logger)


1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
# File 'lib/graphql/schema.rb', line 1379

def default_logger(new_default_logger = NOT_CONFIGURED)
  if NOT_CONFIGURED.equal?(new_default_logger)
    if defined?(@default_logger)
      @default_logger
    elsif superclass.respond_to?(:default_logger)
      superclass.default_logger
    elsif defined?(Rails) && Rails.respond_to?(:logger) && (rails_logger = Rails.logger)
      rails_logger
    else
      def_logger = Logger.new($stdout)
      def_logger.info! # It doesn't output debug info by default
      def_logger
    end
  elsif new_default_logger == nil
    @default_logger = Logger.new(IO::NULL)
  else
    @default_logger = new_default_logger
  end
end

.default_max_page_size(new_default_max_page_size = nil) ⇒ Object



1050
1051
1052
1053
1054
1055
1056
# File 'lib/graphql/schema.rb', line 1050

def default_max_page_size(new_default_max_page_size = nil)
  if new_default_max_page_size
    @default_max_page_size = new_default_max_page_size
  else
    @default_max_page_size || find_inherited_value(:default_max_page_size)
  end
end

.default_page_size(new_default_page_size = nil) ⇒ Object



1075
1076
1077
1078
1079
1080
1081
# File 'lib/graphql/schema.rb', line 1075

def default_page_size(new_default_page_size = nil)
  if new_default_page_size
    @default_page_size = new_default_page_size
  else
    @default_page_size || find_inherited_value(:default_page_size)
  end
end

.default_trace_mode(new_mode = NOT_CONFIGURED) ⇒ Object

Parameters

  • new_mode (Symbol) — If configured, this will be used when context: { trace_mode: ... } isn't set.

:call-seq:

default_trace_mode(Symbol new_mode)


276
277
278
279
280
281
282
283
284
285
286
287
288
# File 'lib/graphql/schema.rb', line 276

def default_trace_mode(new_mode = NOT_CONFIGURED)
  if !NOT_CONFIGURED.equal?(new_mode)
    @default_trace_mode = new_mode
  elsif defined?(@default_trace_mode) &&
      !@default_trace_mode.nil? # This `nil?` check seems necessary because of
                                # Ractors silently initializing @default_trace_mode somehow
    @default_trace_mode
  elsif superclass.respond_to?(:default_trace_mode)
    superclass.default_trace_mode
  else
    :default
  end
end

.deprecated_graphql_definition ⇒ Object



252
253
254
# File 'lib/graphql/schema.rb', line 252

def deprecated_graphql_definition
  graphql_definition(silence_deprecation_warning: true)
end

.description(new_description = nil) ⇒ Object

Returns

  • String, nil

:call-seq:

description(new_description) -> String | nil


472
473
474
475
476
477
478
479
480
# File 'lib/graphql/schema.rb', line 472

def description(new_description = nil)
  if new_description
    @description = new_description
  elsif defined?(@description)
    @description
  else
    find_inherited_value(:description, nil)
  end
end

.detailed_trace?(query) ⇒ Boolean

Tracing::DetailedTrace saves traces when this method returns true.

Parameters

  • query (GraphQL::Query, GraphQL::Execution::Multiplex) — Called with a multiplex when multiple queries are executed at once (with .multiplex)

Returns

  • Boolean — When true, save a detailed trace for this query.

:call-seq:

detailed_trace?(GraphQL::Query | GraphQL::Execution::Multiplex query) -> bool

Returns:

  • (Boolean)


1864
1865
1866
# File 'lib/graphql/schema.rb', line 1864

def detailed_trace?(query)
  raise "#{self} must implement `def.detailed_trace?(query)` to use DetailedTrace. Implement this method in your schema definition."
end

.did_you_mean(new_dym = NOT_CONFIGURED) ⇒ Object

Returns DidYouMean if it's defined. Override this to return nil if you don't want to use DidYouMean



2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
# File 'lib/graphql/schema.rb', line 2273

def did_you_mean(new_dym = NOT_CONFIGURED)
  if NOT_CONFIGURED.equal?(new_dym)
    if defined?(@did_you_mean)
      @did_you_mean
    else
      find_inherited_value(:did_you_mean, defined?(DidYouMean) ? DidYouMean : nil)
    end
  else
    @did_you_mean = new_dym
  end
end

.directive(new_directive) ⇒ Object

Attach a single directive to this schema

Parameters

  • new_directive (Class)

Returns

  • Object — void

:call-seq:

directive(Class new_directive) -> Object


1829
1830
1831
1832
1833
1834
1835
# File 'lib/graphql/schema.rb', line 1829

def directive(new_directive)
  if use_visibility_profile?
    own_directives[new_directive.graphql_name] = new_directive
  else
    add_type_and_traverse(new_directive, root: false)
  end
end

.directives(*new_directives) ⇒ Object

Add several directives at once

Parameters

  • new_directives (Class)

:call-seq:

directives(Class *new_directives)


1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
# File 'lib/graphql/schema.rb', line 1804

def directives(*new_directives)
  if !new_directives.empty?
    new_directives.flatten.each { |d| directive(d) }
  end

  inherited_dirs = find_inherited_value(:directives, default_directives)
  if !own_directives.empty?
    inherited_dirs.merge(own_directives)
  else
    inherited_dirs
  end
end

.disable_introspection_entry_points ⇒ Object



1240
1241
1242
1243
1244
# File 'lib/graphql/schema.rb', line 1240

def disable_introspection_entry_points
  @disable_introspection_entry_points = true
  # TODO: this clears the cache made in `def types`. But this is not a great solution.
  @introspection_system = nil
end

.disable_introspection_entry_points? ⇒ Boolean

Returns:

  • (Boolean)


1258
1259
1260
1261
1262
1263
1264
# File 'lib/graphql/schema.rb', line 1258

def disable_introspection_entry_points?
  if instance_variable_defined?(:@disable_introspection_entry_points)
    @disable_introspection_entry_points
  else
    find_inherited_value(:disable_introspection_entry_points?, false)
  end
end

.disable_schema_introspection_entry_point ⇒ Object



1246
1247
1248
1249
1250
# File 'lib/graphql/schema.rb', line 1246

def disable_schema_introspection_entry_point
  @disable_schema_introspection_entry_point = true
  # TODO: this clears the cache made in `def types`. But this is not a great solution.
  @introspection_system = nil
end

.disable_schema_introspection_entry_point? ⇒ Boolean

Returns:

  • (Boolean)


1266
1267
1268
1269
1270
1271
1272
# File 'lib/graphql/schema.rb', line 1266

def disable_schema_introspection_entry_point?
  if instance_variable_defined?(:@disable_schema_introspection_entry_point)
    @disable_schema_introspection_entry_point
  else
    find_inherited_value(:disable_schema_introspection_entry_point?, false)
  end
end

.disable_type_introspection_entry_point ⇒ Object



1252
1253
1254
1255
1256
# File 'lib/graphql/schema.rb', line 1252

def disable_type_introspection_entry_point
  @disable_type_introspection_entry_point = true
  # TODO: this clears the cache made in `def types`. But this is not a great solution.
  @introspection_system = nil
end

.disable_type_introspection_entry_point? ⇒ Boolean

Returns:

  • (Boolean)


1274
1275
1276
1277
1278
1279
1280
# File 'lib/graphql/schema.rb', line 1274

def disable_type_introspection_entry_point?
  if instance_variable_defined?(:@disable_type_introspection_entry_point)
    @disable_type_introspection_entry_point
  else
    find_inherited_value(:disable_type_introspection_entry_point?, false)
  end
end

.error_handlers ⇒ Object



1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
# File 'lib/graphql/schema.rb', line 1469

def error_handlers
  @error_handlers ||= begin
    new_handler_hash = ->(h, k) {
      h[k] = {
        class: k,
        handler: nil,
        subclass_handlers: Hash.new(&new_handler_hash),
      }
    }
    {
      class: nil,
      handler: nil,
      subclass_handlers: Hash.new(&new_handler_hash),
    }
  end
end

.execute(query_str = nil, **kwargs) ⇒ Object

Execute a query on itself. See the GraphQL::Query constructor for arguments.

query_str may be a query string; alternatively pass document: with a parsed document. The common options are variables:, context:, root_value:, operation_name:, validate:, max_depth:, and max_complexity:. The returned result can be serialized directly as JSON.

Returns

  • GraphQL::Query::Result — query result, ready to be serialized as JSON

:call-seq:

execute(query_str, **kwargs) -> GraphQL::Query::Result


2077
2078
2079
2080
2081
2082
2083
# File 'lib/graphql/schema.rb', line 2077

def execute(query_str = nil, **kwargs)
  if default_execution_next
    execute_next(query_str, **kwargs)
  else
    execute_legacy(query_str, **kwargs)
  end
end

.execute_legacy(query_str = nil, **kwargs) ⇒ Object



2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
# File 'lib/graphql/schema.rb', line 2085

def execute_legacy(query_str = nil, **kwargs)
  if query_str
    kwargs[:query] = query_str
  end
  # Some of the query context _should_ be passed to the multiplex, too
  multiplex_context = if (ctx = kwargs[:context])
    {
      backtrace: ctx[:backtrace],
      tracers: ctx[:tracers],
      trace: ctx[:trace],
      dataloader: ctx[:dataloader],
      trace_mode: ctx[:trace_mode],
    }
  else
    {}
  end
  # Since we're running one query, don't run a multiplex-level complexity analyzer
  all_results = multiplex([kwargs], max_complexity: nil, context: multiplex_context)
  all_results[0]
end

.extra_types(*new_extra_types) ⇒ Object

Parameters

  • new_extra_types (Module) — Type definitions to include in printing and introspection, even though they aren't referenced in the schema

Returns

  • Array<Module> — Type definitions added to this schema

:call-seq:

extra_types(Module *new_extra_types) -> Array[Module]


1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
# File 'lib/graphql/schema.rb', line 1292

def extra_types(*new_extra_types)
  if !new_extra_types.empty?
    new_extra_types = new_extra_types.flatten
    @own_extra_types ||= []
    @own_extra_types.concat(new_extra_types)
  end
  inherited_et = find_inherited_value(:extra_types, nil)
  if inherited_et
    if @own_extra_types
      inherited_et + @own_extra_types
    else
      inherited_et
    end
  else
    @own_extra_types || EMPTY_ARRAY
  end
end

.find(path) ⇒ Object



482
483
484
485
486
487
488
# File 'lib/graphql/schema.rb', line 482

def find(path)
  if !@finder
    @find_cache = {}
    @finder ||= GraphQL::Schema::Finder.new(self)
  end
  @find_cache[path] ||= @finder.find(path)
end

.from_definition(definition_or_path, default_resolve: nil, parser: GraphQL.default_parser, using: {}, base_types: {}) ⇒ Object

Create schema from an IDL schema or file containing an IDL definition.

Parameters

  • definition_or_path (String) — A schema definition string, or a path to a file containing the definition
  • default_resolve (<#call(type, field, obj, args, ctx)>) — A callable for handling field resolution
  • parser (Object) — An object for handling definition string parsing (must respond to parse)
  • using (Hash) — Plugins to attach to the created schema with use(key, value)

Returns

  • Class — the schema described by document

:call-seq:

from_definition(String definition_or_path, #call(type, field, obj, args, ctx) default_resolve:, Object parser:, Hash using:, base_types:) -> Class


229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
# File 'lib/graphql/schema.rb', line 229

def from_definition(definition_or_path, default_resolve: nil, parser: GraphQL.default_parser, using: {}, base_types: {})
  # If the file ends in `.graphql` or `.graphqls`, treat it like a filepath
  if definition_or_path.end_with?(".graphql") || definition_or_path.end_with?(".graphqls")
    GraphQL::Schema::BuildFromDefinition.from_definition_path(
      self,
      definition_or_path,
      default_resolve: default_resolve,
      parser: parser,
      using: using,
      base_types: base_types,
    )
  else
    GraphQL::Schema::BuildFromDefinition.from_definition(
      self,
      definition_or_path,
      default_resolve: default_resolve,
      parser: parser,
      using: using,
      base_types: base_types,
    )
  end
end

.from_introspection(introspection_result) ⇒ Object

Create schema with the result of an introspection query.

Parameters

Returns

  • Class<GraphQL::Schema> — the schema described by input

:call-seq:

from_introspection(Hash introspection_result) -> Class[GraphQL::Schema]


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

def from_introspection(introspection_result)
  GraphQL::Schema::Loader.load(introspection_result)
end

.get_field(type_or_name, field_name, context = null_context, use_visibility_profile = use_visibility_profile?) ) ⇒ Object



963
964
965
966
967
968
969
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
# File 'lib/graphql/schema.rb', line 963

def get_field(type_or_name, field_name, context = null_context, use_visibility_profile = use_visibility_profile?)
  if use_visibility_profile
    profile = Visibility::Profile.from_context(context, self)
    parent_type = case type_or_name
    when String
      profile.type(type_or_name)
    when Module
      type_or_name
    when LateBoundType
      profile.type(type_or_name.name)
    else
      raise GraphQL::InvariantError, "Unexpected field owner for #{field_name.inspect}: #{type_or_name.inspect} (#{type_or_name.class})"
    end
    return profile.field(parent_type, field_name)
  end
  parent_type = case type_or_name
  when LateBoundType
    get_type(type_or_name.name, context)
  when String
    get_type(type_or_name, context)
  when Module
    type_or_name
  else
    raise GraphQL::InvariantError, "Unexpected field owner for #{field_name.inspect}: #{type_or_name.inspect} (#{type_or_name.class})"
  end

  if parent_type.kind.fields? && (field = parent_type.get_field(field_name, context))
    field
  elsif parent_type == query && (entry_point_field = introspection_system.entry_point(name: field_name))
    entry_point_field
  elsif (dynamic_field = introspection_system.dynamic_field(name: field_name))
    dynamic_field
  else
    nil
  end
end

.get_fields(type, context = null_context) ⇒ Object



1000
1001
1002
# File 'lib/graphql/schema.rb', line 1000

def get_fields(type, context = null_context)
  type.fields(context)
end

.get_type(type_name, context = null_context, use_visibility_profile = use_visibility_profile?) ) ⇒ Object

Parameters

  • type_name (String)
  • context (GraphQL::Query::Context) — Used for filtering definitions at query-time
  • use_visibility_profile — Private, for migration to Schema::Visibility

Returns

  • Module, nil — A type, or nil if there's no type called type_name

:call-seq:

get_type(String type_name, GraphQL::Query::Context context, use_visibility_profile) -> Module | nil


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
# File 'lib/graphql/schema.rb', line 575

def get_type(type_name, context = null_context, use_visibility_profile = use_visibility_profile?)
  if use_visibility_profile
    profile = Visibility::Profile.from_context(context, self)
    return profile.type(type_name)
  end
  local_entry = own_types[type_name]
  type_defn = case local_entry
  when nil
    nil
  when Array
    if context.respond_to?(:types) && context.types.is_a?(GraphQL::Schema::Visibility::Profile)
      local_entry
    else
      visible_t = nil
      warden = Warden.from_context(context)
      local_entry.each do |t|
        if warden.visible_type?(t, context)
          if visible_t.nil?
            visible_t = t
          else
            raise DuplicateNamesError.new(
              duplicated_name: type_name, duplicated_definition_1: visible_t.inspect, duplicated_definition_2: t.inspect
            )
          end
        end
      end
      visible_t
    end
  when Module
    local_entry
  else
    raise "Invariant: unexpected own_types[#{type_name.inspect}]: #{local_entry.inspect}"
  end

  type_defn ||
    introspection_system.types[type_name] || # todo context-specific introspection?
    (superclass.respond_to?(:get_type) ? superclass.get_type(type_name, context, use_visibility_profile) : nil)
end

.handle_or_reraise(context, err, object: , arguments: , field: ) ⇒ Object

:nodoc:



1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
# File 'lib/graphql/schema.rb', line 1488

def handle_or_reraise(context, err, object: context[:current_object], arguments: context[:current_arguments], field: context[:current_field]) # :nodoc:
  handler = Execution::Errors.find_handler_for(self, err.class)
  if handler
    arguments = arguments.respond_to?(:keyword_arguments) ? arguments.keyword_arguments : arguments
    if object.is_a?(GraphQL::Schema::Object)
      object = object.object
    end
    handler[:handler].call(err, object, arguments, context, field)
  else
    if (context[:backtrace] || using_backtrace) && !err.is_a?(GraphQL::ExecutionError)
      err = GraphQL::Backtrace::TracedError.new(err, context)
    end

    raise err
  end
end

.has_defined_type?(type_name) ⇒ Boolean

Returns

  • Boolean — Does this schema have any definition for a type named type_name, regardless of visibility?

:call-seq:

has_defined_type?(type_name) -> bool

Returns:

  • (Boolean)


620
621
622
# File 'lib/graphql/schema.rb', line 620

def has_defined_type?(type_name)
  own_types.key?(type_name) || introspection_system.types.key?(type_name) || (superclass.respond_to?(:has_defined_type?) ? superclass.has_defined_type?(type_name) : false)
end

.id_from_object(application_object, graphql_type, context) ⇒ Object

Return a stable ID string for object so that it can be refetched later, using .object_from_id.

GlobalID and SQIDs can both be used to create IDs.

Examples

Example: Using Rails's GlobalID to generate IDs

def self.id_from_object(application_object, graphql_type, context)
  application_object.to_gid_param
end

Parameters

  • application_object (Object) — Some object encountered by GraphQL-Ruby while running a query
  • graphql_type (Class, Module) — The type that GraphQL-Ruby is using for application_object during this query
  • context (GraphQL::Query::Context) — The context for the operation that is currently running

Returns

  • String — A stable identifier which can be passed to .object_from_id later to re-fetch application_object

:call-seq:

id_from_object(Object application_object, Class | Module graphql_type, GraphQL::Query::Context context) -> String


1644
1645
1646
# File 'lib/graphql/schema.rb', line 1644

def id_from_object(application_object, graphql_type, context)
  raise GraphQL::RequiredImplementationMissingError, "#{self.name}.id_from_object(application_object, graphql_type, context) must be implemented to create global ids (tried to create an id for `#{application_object.inspect}`)"
end

.inherited(child_class) ⇒ Object

rubocop:enable Lint/DuplicateMethods



1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
# File 'lib/graphql/schema.rb', line 1567

def inherited(child_class)
  if self == GraphQL::Schema
    child_class.directives(default_directives.values)
    child_class.extend(SubclassGetReferencesTo)
  end
  # Make sure the child class has these built out, so that
  # subclasses can be modified by later calls to `trace_with`
  own_trace_modes.each do |name, _class|
    child_class.own_trace_modes[name] = child_class.build_trace_mode(name)
  end
  child_class.singleton_class.prepend(ResolveTypeWithType)

  if use_visibility_profile?
    vis = self.visibility
    child_class.visibility = vis.dup_for(child_class)
  end
  child_class.null_context = Query::NullContext.new(schema: child_class)
  super
end

.instrument(instrument_step, instrumenter, options = {}) ⇒ Object



1786
1787
1788
1789
1790
1791
1792
1793
1794
# File 'lib/graphql/schema.rb', line 1786

def instrument(instrument_step, instrumenter, options = {})
  warn <<~WARN
  Schema.instrument is deprecated, use `trace_with` instead: https://graphql-ruby.org/queries/tracing.html"
    (From `#{self}.instrument(#{instrument_step}, #{instrumenter})` at #{caller(1, 1).first})

  WARN
  trace_with(Tracing::LegacyHooksTrace)
  own_instrumenters[instrument_step] << instrumenter
end

.instrumenters ⇒ Object



2164
2165
2166
2167
2168
2169
# File 'lib/graphql/schema.rb', line 2164

def instrumenters
  inherited_instrumenters = find_inherited_value(:instrumenters) || Hash.new { |h,k| h[k] = [] }
  inherited_instrumenters.merge(own_instrumenters) do |_step, inherited, own|
    inherited + own
  end
end

.introspection(new_introspection_namespace = nil) ⇒ Object

Pass a custom introspection module here to use it for this schema.

Parameters

  • new_introspection_namespace (Module) — If given, use this module for custom introspection on the schema

Returns

  • Module, nil — The configured namespace, if there is one

:call-seq:

introspection(Module new_introspection_namespace) -> Module | nil


1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
# File 'lib/graphql/schema.rb', line 1016

def introspection(new_introspection_namespace = nil)
  if new_introspection_namespace
    @introspection = new_introspection_namespace
    # reset this cached value:
    @introspection_system = nil
    introspection_system
    self.visibility&.introspection_system_configured(introspection_system)
    @introspection
  else
    @introspection || find_inherited_value(:introspection)
  end
end

.introspection_system ⇒ Object

Returns

:call-seq:

introspection_system() -> Schema::IntrospectionSystem


1035
1036
1037
1038
1039
1040
1041
# File 'lib/graphql/schema.rb', line 1035

def introspection_system
  if !@introspection_system
    @introspection_system = Schema::IntrospectionSystem.new(self)
    @introspection_system.resolve_late_bindings
  end
  @introspection_system
end

.lazy?(obj) ⇒ Boolean

Returns

  • Boolean — True if this object should be lazily resolved

:call-seq:

lazy?(obj) -> bool

Returns:

  • (Boolean)


2251
2252
2253
# File 'lib/graphql/schema.rb', line 2251

def lazy?(obj)
  !!lazy_method_name(obj)
end

.lazy_method_name(obj) ⇒ Object

Returns

  • Symbol, nil — The method name to lazily resolve obj, or nil if obj's class wasn't registered with .lazy_resolve.

:call-seq:

lazy_method_name(obj) -> Symbol | nil


2241
2242
2243
# File 'lib/graphql/schema.rb', line 2241

def lazy_method_name(obj)
  lazy_methods.get(obj)
end

.lazy_resolve(lazy_class, value_method) ⇒ Object



1772
1773
1774
# File 'lib/graphql/schema.rb', line 1772

def lazy_resolve(lazy_class, value_method)
  lazy_methods.set(lazy_class, value_method)
end

.legacy_complexity_cost_calculation_mismatch(multiplex, future_complexity_cost, legacy_complexity_cost) ⇒ Object

Implement this method in your schema to handle mismatches when :compare is used.

See Query::Context#add_error Adding an error to the response to notify the client See Query::Context#response_extensions Adding key-value pairs to the response "extensions" => { ... }

Examples

Example: Logging the mismatch

def self.legacy_cost_calculation_mismatch(multiplex, future_cost, legacy_cost)
  client_id = multiplex.context[:api_client].id
  operation_names = multiplex.queries.map { |q| q.selected_operation_name || "anonymous" }.join(", ")
  Stats.increment(:complexity_mismatch, tags: { client: client_id, ops: operation_names })
  legacy_cost
end

Parameters

  • multiplex (GraphQL::Execution::Multiplex)
  • future_complexity_cost (Integer)
  • legacy_complexity_cost (Integer)

Returns

  • Integer — the cost to use for this query (probably one of future_complexity_cost or legacy_complexity_cost)

:call-seq:

legacy_complexity_cost_calculation_mismatch(GraphQL::Execution::Multiplex multiplex, Integer future_complexity_cost, Integer legacy_complexity_cost) -> Integer


2667
2668
2669
# File 'lib/graphql/schema.rb', line 2667

def legacy_complexity_cost_calculation_mismatch(multiplex, future_complexity_cost, legacy_complexity_cost)
  raise "Implement #{self}.legacy_complexity_cost(multiplex, future_complexity_cost, legacy_complexity_cost) to handle this mismatch (#{future_complexity_cost} vs. #{legacy_complexity_cost}) and return a value to use"
end

.legacy_invalid_empty_selections_on_union(query) ⇒ Object

This method is called during validation when a previously-allowed, but non-spec query is encountered where a union field has no child selections on it.

If legacy_invalid_empty_selections_on_union_with_type is overridden, this method will not be called.

You should implement this method or legacy_invalid_empty_selections_on_union_with_type to log the violation so that you can contact clients and notify them about changing their queries. Then return a suitable value to tell GraphQL-Ruby how to continue.

Parameters

  • query (GraphQL::Query)

Returns

  • :return_validation_error — Let GraphQL-Ruby return the (new) normal validation error for this query
  • String — A validation error to return for this query
  • nil — Don't send the client an error, continue the legacy behavior (allow this query to execute)

:call-seq:

legacy_invalid_empty_selections_on_union(GraphQL::Query query) -> :return_validation_error | String | nil


2339
2340
2341
# File 'lib/graphql/schema.rb', line 2339

def legacy_invalid_empty_selections_on_union(query)
  raise "Implement `def self.legacy_invalid_empty_selections_on_union_with_type(query, type)` or `def self.legacy_invalid_empty_selections_on_union(query)` to handle this scenario"
end

.legacy_invalid_empty_selections_on_union_with_type(query, type) ⇒ Object

This method is called during validation when a previously-allowed, but non-spec query is encountered where a union field has no child selections on it.

You should implement this method to log the violation so that you can contact clients and notify them about changing their queries. Then return a suitable value to tell GraphQL-Ruby how to continue.

Parameters

  • query (GraphQL::Query)
  • type (Module) — A GraphQL type definition

Returns

  • :return_validation_error — Let GraphQL-Ruby return the (new) normal validation error for this query
  • String — A validation error to return for this query
  • nil — Don't send the client an error, continue the legacy behavior (allow this query to execute)

:call-seq:

legacy_invalid_empty_selections_on_union_with_type(GraphQL::Query query, Module type) -> :return_validation_error | String | nil


2363
2364
2365
# File 'lib/graphql/schema.rb', line 2363

def legacy_invalid_empty_selections_on_union_with_type(query, type)
  legacy_invalid_empty_selections_on_union(query)
end

.legacy_invalid_field_conflicts(query, node1, node2) ⇒ Object

This method is called when the query has two fields with the same response name but different names or arguments, which previous versions of GraphQL-Ruby allowed. See .allow_legacy_invalid_field_conflicts.

You should implement this method to log the violation so that you can contact clients and notify them about changing their queries. Then return a suitable value to tell GraphQL-Ruby how to continue.

Parameters

  • query (GraphQL::Query)
  • node1 (GraphQL::Language::Nodes::Field) — This node is recognized as conflicting. You might call .line and .col for custom error reporting.
  • node2 (GraphQL::Language::Nodes::Field) — The other node recognized as conflicting.

Returns

  • :return_validation_error — Let GraphQL-Ruby return the (new) normal validation error for this query
  • String — A validation error to return for this query
  • nil — Don't send the client an error, continue the legacy behavior (allow this query to execute)

:call-seq:

legacy_invalid_field_conflicts(GraphQL::Query query, GraphQL::Language::Nodes::Field node1, GraphQL::Language::Nodes::Field node2) -> :return_validation_error | String | nil


2540
2541
2542
# File 'lib/graphql/schema.rb', line 2540

def legacy_invalid_field_conflicts(query, node1, node2)
  raise "Implement #{self}.legacy_invalid_field_conflicts to handle this invalid selection"
end

.legacy_invalid_return_type_conflicts(query, type1, type2, node1, node2) ⇒ Object

This method is called when the query contains fields which don't contain matching scalar types. This was previously allowed by GraphQL-Ruby but it's a violation of the GraphQL spec.

You should implement this method to log the violation so that you observe usage of these fields. Fixing this scenario might mean adding new fields, and telling clients to use those fields. (Changing the field return type would be a breaking change, but if it works for your client use cases, that might work, too.)

Parameters

  • query (GraphQL::Query)
  • type1 (Module) — A GraphQL type definition
  • type2 (Module) — A GraphQL type definition
  • node1 (GraphQL::Language::Nodes::Field) — This node is recognized as conflicting. You might call .line and .col for custom error reporting.
  • node2 (GraphQL::Language::Nodes::Field) — The other node recognized as conflicting.

Returns

  • :return_validation_error — Let GraphQL-Ruby return the (new) normal validation error for this query
  • String — A validation error to return for this query
  • nil — Don't send the client an error, continue the legacy behavior (allow this query to execute)

:call-seq:

legacy_invalid_return_type_conflicts(GraphQL::Query query, Module type1, Module type2, GraphQL::Language::Nodes::Field node1, GraphQL::Language::Nodes::Field node2) -> :return_validation_error | String | nil


2480
2481
2482
# File 'lib/graphql/schema.rb', line 2480

def legacy_invalid_return_type_conflicts(query, type1, type2, node1, node2)
  raise "Implement #{self}.legacy_invalid_return_type_conflicts to handle this invalid selection"
end

.legacy_invalid_variable_usages(query, variable_definition, argument) ⇒ Object

This method is called when the query uses a variable in a way which the GraphQL spec doesn't allow, but which previous versions of GraphQL-Ruby allowed. See .allow_legacy_invalid_variable_usages.

You should implement this method to log the violation so that you can contact clients and notify them about changing their queries. Then return a suitable value to tell GraphQL-Ruby how to continue.

Parameters

  • query (GraphQL::Query)
  • variable_definition (GraphQL::Language::Nodes::VariableDefinition) — The definition of the variable
  • argument (GraphQL::Language::Nodes::Argument) — The argument which uses the variable. You might call .line and .col for custom error reporting.

Returns

  • :return_validation_error — Let GraphQL-Ruby return the (new) normal validation error for this query
  • String — A validation error to return for this query
  • nil — Don't send the client an error, continue the legacy behavior (allow this query to execute)

:call-seq:

legacy_invalid_variable_usages(GraphQL::Query query, GraphQL::Language::Nodes::VariableDefinition variable_definition, GraphQL::Language::Nodes::Argument argument) -> :return_validation_error | String | nil


2423
2424
2425
# File 'lib/graphql/schema.rb', line 2423

def legacy_invalid_variable_usages(query, variable_definition, argument)
  raise "Implement #{self}.legacy_invalid_variable_usages to handle this invalid variable usage"
end

.load_type(type_name, ctx) ⇒ Object

Called when a type is needed by name at runtime



1662
1663
1664
# File 'lib/graphql/schema.rb', line 1662

def load_type(type_name, ctx)
  get_type(type_name, ctx)
end

.logger_for(context) ⇒ Object

Parameters

  • context (GraphQL::Query::Context, nil)

Returns

  • Logger — A logger to use for this context configuration, falling back to .default_logger

:call-seq:

logger_for(GraphQL::Query::Context | nil context) -> Logger


1409
1410
1411
1412
1413
1414
1415
1416
1417
# File 'lib/graphql/schema.rb', line 1409

def logger_for(context)
  if context && context[:logger] == false
    Logger.new(IO::NULL)
  elsif context && (l = context[:logger])
    l
  else
    default_logger
  end
end

.max_complexity_count_introspection_fields ⇒ Object



1194
1195
1196
1197
1198
1199
1200
# File 'lib/graphql/schema.rb', line 1194

def max_complexity_count_introspection_fields
  if defined?(@max_complexity_count_introspection_fields)
    @max_complexity_count_introspection_fields
  else
    find_inherited_value(:max_complexity_count_introspection_fields, true)
  end
end

.max_query_string_tokens(new_max_tokens = NOT_CONFIGURED) ⇒ Object

A limit on the number of tokens to accept on incoming query strings. Use this to prevent parsing maliciously-large query strings.

Returns

  • nil, Integer

:call-seq:

max_query_string_tokens(new_max_tokens) -> nil | Integer


1067
1068
1069
1070
1071
1072
1073
# File 'lib/graphql/schema.rb', line 1067

def max_query_string_tokens(new_max_tokens = NOT_CONFIGURED)
  if NOT_CONFIGURED.equal?(new_max_tokens)
    defined?(@max_query_string_tokens) ? @max_query_string_tokens : find_inherited_value(:max_query_string_tokens)
  else
    @max_query_string_tokens = new_max_tokens
  end
end

.multiplex(queries, **kwargs) ⇒ Object

Execute several queries on itself, concurrently.

See the GraphQL::Query constructor for query keyword arguments. Multiplex-level execution is handled by the interpreter's GraphQL::Execution::Interpreter.run_all method.

Examples

Example: Run several queries at once

context = { ... }
queries = [
  { query: params[:query_1], variables: params[:variables_1], context: context },
  { query: params[:query_2], variables: params[:variables_2], context: context },
]
results = MySchema.multiplex(queries)
render json: {
  result_1: results[0],
  result_2: results[1],
}

Parameters

  • queries (Array<Hash>) — Keyword arguments for each query

Options

  • kwargs.:context (Hash) — ({}) Multiplex-level context
  • kwargs.:max_complexity (nil, Integer) — (nil)

Returns

  • Array<GraphQL::Query::Result> — One result for each query in the input

:call-seq:

multiplex(Array[Hash] queries, **kwargs) -> Array[GraphQL::Query::Result]


2144
2145
2146
2147
2148
2149
2150
# File 'lib/graphql/schema.rb', line 2144

def multiplex(queries, **kwargs)
  if @default_execution_next
    multiplex_next(queries, **kwargs)
  else
    GraphQL::Execution::Interpreter.run_all(self, queries, **kwargs)
  end
end

.multiplex_analyzer(new_analyzer) ⇒ Object

See GraphQL::Analysis the analysis system

Parameters

  • new_analyzer (Class<GraphQL::Analysis::Analyzer>) — An analyzer to run on multiplexes to this schema

:call-seq:

multiplex_analyzer(Class[GraphQL::Analysis::Analyzer] new_analyzer)


2047
2048
2049
# File 'lib/graphql/schema.rb', line 2047

def multiplex_analyzer(new_analyzer)
  own_multiplex_analyzers << new_analyzer
end

.multiplex_analyzers ⇒ Object



2051
2052
2053
# File 'lib/graphql/schema.rb', line 2051

def multiplex_analyzers
  find_inherited_value(:multiplex_analyzers, EMPTY_ARRAY) + own_multiplex_analyzers
end

.mutation(new_mutation_object = nil, &lazy_load_block) ⇒ Object

Get or set the root mutation object for this schema.

Examples

Example: Using Types::Mutation as the entry-point

mutation { Types::Mutation }

Parameters

  • new_mutation_object (Class<GraphQL::Schema::Object>) — The root type to use for mutations
  • lazy_load_block — If a block is given, then it will be called when GraphQL-Ruby needs the root mutation type.

Returns

  • Class<GraphQL::Schema::Object>, nil — The configured mutation root type, if there is one.

:call-seq:

mutation(Class[GraphQL::Schema::Object] new_mutation_object, &lazy_load_block) -> Class[GraphQL::Schema::Object] | nil


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
# File 'lib/graphql/schema.rb', line 720

def mutation(new_mutation_object = nil, &lazy_load_block)
  if new_mutation_object || block_given?
    if @mutation_object
      dup_defn = new_mutation_object || yield
      raise GraphQL::Error, "Second definition of `mutation(...)` (#{dup_defn.inspect}) is invalid, already configured with #{@mutation_object.inspect}"
    elsif use_visibility_profile?
      if block_given?
        if visibility.preload?
          @mutation_object = lazy_load_block.call
          self.visibility.mutation_configured(@mutation_object)
        else
          @mutation_object = lazy_load_block
        end
      else
        @mutation_object = new_mutation_object
        self.visibility.mutation_configured(@mutation_object)
      end
    else
      @mutation_object = new_mutation_object || lazy_load_block.call
      add_type_and_traverse(@mutation_object, root: true)
    end
    nil
  elsif @mutation_object.is_a?(Proc)
    @mutation_object = @mutation_object.call
    self.visibility&.mutation_configured(@mutation_object)
    @mutation_object
  else
    @mutation_object || find_inherited_value(:mutation)
  end
end

.mutation_execution_strategy(new_mutation_execution_strategy = nil, deprecation_warning: true) ⇒ Object



1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
# File 'lib/graphql/schema.rb', line 1095

def mutation_execution_strategy(new_mutation_execution_strategy = nil, deprecation_warning: true)
  if deprecation_warning
    warn "GraphQL::Schema.mutation_execution_strategy is deprecated without replacement. Use `GraphQL::Query.new` directly to create and execute a custom query instead."
      warn "  #{caller(1, 1).first}"
  end
  if new_mutation_execution_strategy
    @mutation_execution_strategy = new_mutation_execution_strategy
  else
    @mutation_execution_strategy || (superclass.respond_to?(:mutation_execution_strategy) ? superclass.mutation_execution_strategy(deprecation_warning: false) : self.default_execution_strategy)
  end
end

.new_trace(mode: nil, **options) ⇒ Object

Create a trace instance which will include the trace modules specified for the optional mode.

If no mode: is given, then default_trace_mode will be used.

If this schema is using Tracing::DetailedTrace and .detailed_trace? returns true, then DetailedTrace's mode will override the passed-in mode.

Parameters

  • mode (Symbol) — Trace modules for this trade mode will be included
  • options (Hash) — Keywords that will be passed to the tracing class during #initialize

Returns

  • Tracing::Trace

:call-seq:

new_trace(Symbol mode:, Hash **options) -> Tracing::Trace


1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
# File 'lib/graphql/schema.rb', line 1993

def new_trace(mode: nil, **options)
  should_sample = if detailed_trace
    if (query = options[:query])
      detailed_trace?(query)
    elsif (multiplex = options[:multiplex])
      if multiplex.queries.length == 1
        detailed_trace?(multiplex.queries.first)
      else
        detailed_trace?(multiplex)
      end
    end
  else
    false
  end

  if should_sample
    mode = detailed_trace.trace_mode
  else
    target = options[:query] || options[:multiplex]
    mode ||= target && target.context[:trace_mode]
  end

  trace_mode = mode || default_trace_mode
  base_trace_options = trace_options_for(trace_mode)
  trace_options = base_trace_options.merge(options)
  trace_class_for_mode = trace_class_for(trace_mode, build: true)
  trace_class_for_mode.new(**trace_options)
end

.object_from_id(object_id, context) ⇒ Object

Fetch an object based on an incoming ID and the current context. This method should return an object from your application, or return nil if there is no object or the object shouldn't be available to this operation.

See id_from_object which produces these IDs

Examples

Example: Fetching an object with Rails's GlobalID

def self.object_from_id(object_id, _context)
  GlobalID.find(global_id)
  # TODO: use `context[:current_user]` to determine if this object is authorized.
end

Parameters

  • object_id (String) — The ID to fetch an object for. This may be client-provided (as in node(id: ...) or loads:) or previously stored by the schema (eg, by the ObjectCache)
  • context (GraphQL::Query::Context) — The context for the currently-executing operation

Returns

  • Object, nil — The application which object_id references, or nil if there is no object or the current operation shouldn't have access to the object

:call-seq:

object_from_id(String object_id, GraphQL::Query::Context context) -> Object | nil


1614
1615
1616
# File 'lib/graphql/schema.rb', line 1614

def object_from_id(object_id, context)
  raise GraphQL::RequiredImplementationMissingError, "#{self.name}.object_from_id(object_id, context) must be implemented to load by ID (tried to load from id `#{object_id}`)"
end

.orphan_types(*new_orphan_types) ⇒ Object

Tell the schema about these types so that they can be registered as implementations of interfaces in the schema.

This method must be used when an object type is connected to the schema as an interface implementor but not as a return type of a field. In that case, if the object type isn't registered here, GraphQL-Ruby won't be able to find it.

Parameters

  • new_orphan_types (Array<Class<GraphQL::Schema::Object>>) — Object types to register as implementations of interfaces in the schema.

Returns

  • Array<Class<GraphQL::Schema::Object>> — All previously-registered orphan types for this schema

:call-seq:

orphan_types(Array[Class[GraphQL::Schema::Object]] *new_orphan_types) -> Array[Class[GraphQL::Schema::Object]]


1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
# File 'lib/graphql/schema.rb', line 1325

def orphan_types(*new_orphan_types)
  if !new_orphan_types.empty?
    new_orphan_types = new_orphan_types.flatten
    non_object_types = new_orphan_types.reject { |ot| ot.is_a?(Class) && ot < GraphQL::Schema::Object }
    if !non_object_types.empty?
      raise ArgumentError, <<~ERR
        Only object type classes should be added as `orphan_types(...)`.

        - Remove these no-op types from `orphan_types`: #{non_object_types.map { |t| "#{t.inspect} (#{t.kind.name})"}.join(", ")}
        - See https://graphql-ruby.org/type_definitions/interfaces.html#orphan-types

        To add other types to your schema, you might want `extra_types`: https://graphql-ruby.org/schema/definition.html#extra-types
      ERR
    end
    add_type_and_traverse(new_orphan_types, root: false) unless use_visibility_profile?
    own_orphan_types.concat(new_orphan_types.flatten)
    self.visibility&.orphan_types_configured(new_orphan_types)
  end

  inherited_ot = find_inherited_value(:orphan_types, nil)
  if inherited_ot
    if !own_orphan_types.empty?
      inherited_ot + own_orphan_types
    else
      inherited_ot
    end
  else
    own_orphan_types
  end
end

.own_trace_modes ⇒ Object



345
346
347
# File 'lib/graphql/schema.rb', line 345

def own_trace_modes
  @own_trace_modes ||= {}
end

.own_trace_modules ⇒ Object



377
378
379
# File 'lib/graphql/schema.rb', line 377

def own_trace_modules
  @own_trace_modules ||= Hash.new { |h, k| h[k] = [] }
end

.parse_error(parse_err, ctx) ⇒ Object

A function to call when .execute receives an invalid query string

The default is to add the error to context.errors

Parameters

  • parse_err (GraphQL::ParseError) — The error encountered during parsing
  • ctx (GraphQL::Query::Context) — The context for the query where the error occurred

Returns

  • Object — void

:call-seq:

parse_error(GraphQL::ParseError parse_err, GraphQL::Query::Context ctx) -> Object


1768
1769
1770
# File 'lib/graphql/schema.rb', line 1768

def parse_error(parse_err, ctx)
  ctx.errors.push(parse_err)
end

.plugins ⇒ Object



515
516
517
# File 'lib/graphql/schema.rb', line 515

def plugins
  find_inherited_value(:plugins, EMPTY_ARRAY) + own_plugins
end

.possible_types(type = nil, context = null_context, use_visibility_profile = use_visibility_profile?) ) ⇒ Object

Parameters

  • type (Module) — The type definition whose possible types you want to see
  • context (GraphQL::Query::Context) — used for filtering visible possible types at runtime
  • use_visibility_profile — Private, for migration to Schema::Visibility

Returns

  • Hash<String, Module> — All possible types, if no type is given.
  • Array<Module> — Possible types for type, if it's given.

:call-seq:

possible_types(Module type, GraphQL::Query::Context context, use_visibility_profile) -> Hash[String, Module] | Array[Module]


880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
# File 'lib/graphql/schema.rb', line 880

def possible_types(type = nil, context = null_context, use_visibility_profile = use_visibility_profile?)
  if use_visibility_profile
    if type
      return Visibility::Profile.from_context(context, self).possible_types(type)
    else
      raise "Schema.possible_types is not implemented for `use_visibility_profile?`"
    end
  end
  if type
    # TODO duck-typing `.possible_types` would probably be nicer here
    if type.kind.union?
      type.possible_types(context: context)
    else
      stored_possible_types = own_possible_types[type]
      visible_possible_types = if stored_possible_types && type.kind.interface?
        stored_possible_types.select do |possible_type|
          possible_type.interfaces(context).include?(type)
        end
      else
        stored_possible_types
      end
      visible_possible_types ||
        introspection_system.possible_types[type] ||
        (
          superclass.respond_to?(:possible_types) ?
            superclass.possible_types(type, context, use_visibility_profile) :
            EMPTY_ARRAY
        )
    end
  else
    find_inherited_value(:possible_types, EMPTY_HASH)
      .merge(own_possible_types)
      .merge(introspection_system.possible_types)
  end
end

.query(new_query_object = nil, &lazy_load_block) ⇒ Object

Get or set the root query object for this schema.

Examples

Example: Using Types::Query as the entry-point

query { Types::Query }

Parameters

  • new_query_object (Class<GraphQL::Schema::Object>) — The root type to use for queries
  • lazy_load_block — If a block is given, then it will be called when GraphQL-Ruby needs the root query type.

Returns

  • Class<GraphQL::Schema::Object>, nil — The configured query root type, if there is one.

:call-seq:

query(Class[GraphQL::Schema::Object] new_query_object, &lazy_load_block) -> Class[GraphQL::Schema::Object] | nil


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
# File 'lib/graphql/schema.rb', line 668

def query(new_query_object = nil, &lazy_load_block)
  if new_query_object || block_given?
    if @query_object
      dup_defn = new_query_object || yield
      raise GraphQL::Error, "Second definition of `query(...)` (#{dup_defn.inspect}) is invalid, already configured with #{@query_object.inspect}"
    elsif use_visibility_profile?
      if block_given?
        if visibility.preload?
          @query_object = lazy_load_block.call
          self.visibility.query_configured(@query_object)
        else
          @query_object = lazy_load_block
        end
      else
        @query_object = new_query_object
        self.visibility.query_configured(@query_object)
      end
    else
      @query_object = new_query_object || lazy_load_block.call
      add_type_and_traverse(@query_object, root: true)
    end
    nil
  elsif @query_object.is_a?(Proc)
    @query_object = @query_object.call
    self.visibility&.query_configured(@query_object)
    @query_object
  else
    @query_object || find_inherited_value(:query)
  end
end

.query_analyzer(new_analyzer) ⇒ Object

See GraphQL::Analysis the analysis system

Parameters

  • new_analyzer (Class<GraphQL::Analysis::Analyzer>) — An analyzer to run on queries to this schema

:call-seq:

query_analyzer(Class[GraphQL::Analysis::Analyzer] new_analyzer)


2030
2031
2032
# File 'lib/graphql/schema.rb', line 2030

def query_analyzer(new_analyzer)
  own_query_analyzers << new_analyzer
end

.query_analyzers ⇒ Object



2034
2035
2036
2037
# File 'lib/graphql/schema.rb', line 2034

def query_analyzers
  inherited_qa = find_inherited_value(:query_analyzers, EMPTY_ARRAY)
  inherited_qa.empty? ? own_query_analyzers : (inherited_qa + own_query_analyzers)
end

.query_class(new_query_class = NOT_CONFIGURED) ⇒ Object

Parameters

  • new_query_class (Class<GraphQL::Query>) — A subclass to use when executing queries

:call-seq:

query_class(Class[GraphQL::Query] new_query_class)


1163
1164
1165
1166
1167
1168
1169
# File 'lib/graphql/schema.rb', line 1163

def query_class(new_query_class = NOT_CONFIGURED)
  if NOT_CONFIGURED.equal?(new_query_class)
    @query_class || (superclass.respond_to?(:query_class) ? superclass.query_class : GraphQL::Query)
  else
    @query_class = new_query_class
  end
end

.query_execution_strategy(new_query_execution_strategy = nil, deprecation_warning: true) ⇒ Object



1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
# File 'lib/graphql/schema.rb', line 1083

def query_execution_strategy(new_query_execution_strategy = nil, deprecation_warning: true)
  if deprecation_warning
    warn "GraphQL::Schema.query_execution_strategy is deprecated without replacement. Use `GraphQL::Query.new` directly to create and execute a custom query instead."
    warn "  #{caller(1, 1).first}"
  end
  if new_query_execution_strategy
    @query_execution_strategy = new_query_execution_strategy
  else
    @query_execution_strategy || (superclass.respond_to?(:query_execution_strategy) ? superclass.query_execution_strategy(deprecation_warning: false) : self.default_execution_strategy)
  end
end

.query_stack_error(query, err) ⇒ Object

Called when execution encounters a SystemStackError. By default, it adds a client-facing error to the response. You could modify this method to report this error to your bug tracker.

Parameters

  • query (GraphQL::Query)
  • err (SystemStackError)

Returns

  • void

:call-seq:

query_stack_error(GraphQL::Query query, SystemStackError err) -> void


2197
2198
2199
# File 'lib/graphql/schema.rb', line 2197

def query_stack_error(query, err)
  query.context.errors.push(GraphQL::ExecutionError.new("This query is too large to execute."))
end

.references_to(to_type = nil, from: nil) ⇒ Object



938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
# File 'lib/graphql/schema.rb', line 938

def references_to(to_type = nil, from: nil)
  if to_type
    if from
      refs = own_references_to[to_type] ||= []
      refs << from
    else
      get_references_to(to_type) || EMPTY_ARRAY
    end
  else
    # `@own_references_to` can be quite large for big schemas,
    # and generally speaking, we won't inherit any values.
    # So optimize the most common case -- don't create a duplicate Hash.
    inherited_value = find_inherited_value(:references_to, EMPTY_HASH)
    if !inherited_value.empty?
      inherited_value.merge(own_references_to)
    else
      own_references_to
    end
  end
end

.rescue_from(*err_classes, &handler_block) ⇒ Object

Register a handler for errors raised during execution. The handlers can return a new value or raise a new error.

Examples

Example: Handling "not found" with a client-facing error

rescue_from(ActiveRecord::NotFound) { raise GraphQL::ExecutionError, "An object could not be found" }

Parameters

  • err_classes (Array<StandardError>) — Classes which should be rescued by handler_block
  • handler_block — The code to run when one of those errors is raised during execution

Yields

  • error (StandardError) — An instance of one of the configured err_classes
  • object (Object) — The current application object in the query when the error was raised
  • arguments (GraphQL::Query::Arguments) — The current field arguments when the error was raised
  • context (GraphQL::Query::Context) — The context for the currently-running operation
  • Object — Some object to use in the place where this error was raised

Raises

  • GraphQL::ExecutionError — In the handler, raise to add a client-facing error to the response
  • StandardError — In the handler, raise to crash the query with a developer-facing error

:call-seq:

rescue_from(Array[StandardError] *err_classes, &handler_block)


1463
1464
1465
1466
1467
# File 'lib/graphql/schema.rb', line 1463

def rescue_from(*err_classes, &handler_block)
  err_classes.each do |err_class|
    Execution::Errors.register_rescue_from(err_class, error_handlers[:subclass_handlers], handler_block)
  end
end

.resolve_type(abstract_type, application_object, context) ⇒ Object

GraphQL-Ruby calls this method during execution when it needs the application to determine the type to use for an object.

Usually, this object was returned from a field whose return type is an GraphQL::Schema::Interface or a GraphQL::Schema::Union. But this method is called in other cases, too -- for example, when GraphQL::Schema::Argument#loads cases an object to be directly loaded from the database.

Examples

Example: Returning a GraphQL type based on the object's class name

class MySchema < GraphQL::Schema
  def resolve_type(_abs_type, object, _context)
    graphql_type_name = "Types::#{object.class.name}Type"
    graphql_type_name.constantize # If this raises a NameError, then come implement special cases in this method
  end
end

Parameters

  • abstract_type (Class, Module, nil) — The Interface or Union type which is being resolved, if there is one
  • application_object (Object) — The object returned from a field whose type must be determined
  • context (GraphQL::Query::Context) — The query context for the currently-executing query

Returns

  • Class<GraphQL::Schema::Object> — The Object type definition to use for obj

:call-seq:

resolve_type(Class | Module | nil abstract_type, Object application_object, GraphQL::Query::Context context) -> Class[GraphQL::Schema::Object]


1562
1563
1564
# File 'lib/graphql/schema.rb', line 1562

def resolve_type(abstract_type, application_object, context)
  raise GraphQL::RequiredImplementationMissingError, "#{self.name}.resolve_type(abstract_type, application_object, context) must be implemented to use Union types, Interface types, `loads:`, or `run_partials` (tried to resolve: #{abstract_type.name})"
end

.resolves_lazies? ⇒ Boolean

Returns:

  • (Boolean)


1776
1777
1778
1779
1780
1781
1782
1783
1784
# File 'lib/graphql/schema.rb', line 1776

def resolves_lazies?
  lazy_method_count = 0
  lazy_methods.each do |k, v|
    if !v.nil?
      lazy_method_count += 1
    end
  end
  lazy_method_count > 2
end

.root_type_for_operation(operation) ⇒ Object

:nodoc:



806
807
808
809
810
811
812
813
814
815
816
817
# File 'lib/graphql/schema.rb', line 806

def root_type_for_operation(operation) # :nodoc:
  case operation
  when "query"
    query
  when "mutation"
    mutation
  when "subscription"
    subscription
  else
    raise ArgumentError, "unknown operation type: #{operation}"
  end
end

.root_types ⇒ Object

Returns

  • Array<Class> — The root types (query, mutation, subscription) defined for this schema

:call-seq:

root_types() -> Array[Class]


825
826
827
828
829
830
831
# File 'lib/graphql/schema.rb', line 825

def root_types
  if use_visibility_profile?
    [query, mutation, subscription].compact
  else
    @root_types
  end
end

.sanitized_printer(new_sanitized_printer = nil) ⇒ Object



2055
2056
2057
2058
2059
2060
2061
# File 'lib/graphql/schema.rb', line 2055

def sanitized_printer(new_sanitized_printer = nil)
  if new_sanitized_printer
    @own_sanitized_printer = new_sanitized_printer
  else
    @own_sanitized_printer || GraphQL::Language::SanitizedPrinter
  end
end

.schema_directive(dir_class, **options) ⇒ Object



1652
1653
1654
1655
# File 'lib/graphql/schema.rb', line 1652

def schema_directive(dir_class, **options)
  @own_schema_directives ||= []
  Member::HasDirectives.add_directive(self, @own_schema_directives, dir_class, options)
end

.schema_directives ⇒ Object



1657
1658
1659
# File 'lib/graphql/schema.rb', line 1657

def schema_directives
  Member::HasDirectives.get_directives(self, @own_schema_directives, :schema_directives)
end

.static_validator ⇒ Object



490
491
492
# File 'lib/graphql/schema.rb', line 490

def static_validator
  GraphQL::StaticValidation::Validator.new(schema: self)
end

.subscription(new_subscription_object = nil, &lazy_load_block) ⇒ Object

Get or set the root subscription object for this schema.

Examples

Example: Using Types::Subscription as the entry-point

subscription { Types::Subscription }

Parameters

  • new_subscription_object (Class<GraphQL::Schema::Object>) — The root type to use for subscriptions
  • lazy_load_block — If a block is given, then it will be called when GraphQL-Ruby needs the root subscription type.

Returns

  • Class<GraphQL::Schema::Object>, nil — The configured subscription root type, if there is one.

:call-seq:

subscription(Class[GraphQL::Schema::Object] new_subscription_object, &lazy_load_block) -> Class[GraphQL::Schema::Object] | nil


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
800
801
802
803
804
# File 'lib/graphql/schema.rb', line 772

def subscription(new_subscription_object = nil, &lazy_load_block)
  if new_subscription_object || block_given?
    if @subscription_object
      dup_defn = new_subscription_object || yield
      raise GraphQL::Error, "Second definition of `subscription(...)` (#{dup_defn.inspect}) is invalid, already configured with #{@subscription_object.inspect}"
    elsif use_visibility_profile?
      if block_given?
        if visibility.preload?
          @subscription_object = lazy_load_block.call
          visibility.subscription_configured(@subscription_object)
        else
          @subscription_object = lazy_load_block
        end
      else
        @subscription_object = new_subscription_object
        self.visibility.subscription_configured(@subscription_object)
      end
      add_subscription_extension_if_necessary
    else
      @subscription_object = new_subscription_object || lazy_load_block.call
      add_subscription_extension_if_necessary
      add_type_and_traverse(@subscription_object, root: true)
    end
    nil
  elsif @subscription_object.is_a?(Proc)
    @subscription_object = @subscription_object.call
    add_subscription_extension_if_necessary
    self.visibility.subscription_configured(@subscription_object)
    @subscription_object
  else
    @subscription_object || find_inherited_value(:subscription)
  end
end

.subscription_execution_strategy(new_subscription_execution_strategy = nil, deprecation_warning: true) ⇒ Object



1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
# File 'lib/graphql/schema.rb', line 1107

def subscription_execution_strategy(new_subscription_execution_strategy = nil, deprecation_warning: true)
  if deprecation_warning
    warn "GraphQL::Schema.subscription_execution_strategy is deprecated without replacement. Use `GraphQL::Query.new` directly to create and execute a custom query instead."
    warn "  #{caller(1, 1).first}"
  end
  if new_subscription_execution_strategy
    @subscription_execution_strategy = new_subscription_execution_strategy
  else
    @subscription_execution_strategy || (superclass.respond_to?(:subscription_execution_strategy) ? superclass.subscription_execution_strategy(deprecation_warning: false) : self.default_execution_strategy)
  end
end

.subscriptions(inherited: true) ⇒ Object

Returns

  • GraphQL::Subscriptions

:call-seq:

subscriptions(inherited:) -> GraphQL::Subscriptions


262
263
264
# File 'lib/graphql/schema.rb', line 262

def subscriptions(inherited: true)
  defined?(@subscriptions) ? @subscriptions : (inherited ? find_inherited_value(:subscriptions, nil) : nil)
end

.subscriptions=(new_implementation) ⇒ Object



266
267
268
# File 'lib/graphql/schema.rb', line 266

def subscriptions=(new_implementation)
  @subscriptions = new_implementation
end

.sync_lazy(value) ⇒ Object

Override this method to handle lazy objects in a custom way.

Parameters

  • value (Object) — an instance of a class registered with .lazy_resolve

Returns

  • Object — A GraphQL-ready (non-lazy) object


2225
2226
2227
2228
2229
2230
2231
2232
2233
# File 'lib/graphql/schema.rb', line 2225

def sync_lazy(value) # :nodoc:
  lazy_method = lazy_method_name(value)
  if lazy_method
    synced_value = value.public_send(lazy_method)
    sync_lazy(synced_value)
  else
    value
  end
end

.to_definition(context: {}) ⇒ Object

Return the GraphQL IDL for the schema

Parameters

  • context (Hash)

Returns

  • String

:call-seq:

to_definition(Hash context:) -> String


450
451
452
# File 'lib/graphql/schema.rb', line 450

def to_definition(context: {})
  GraphQL::Schema::Printer.print_schema(self, context: context)
end

.to_document ⇒ Object

Return the GraphQL::Language::Document IDL AST for the schema

Returns

  • GraphQL::Language::Document

:call-seq:

to_document() -> GraphQL::Language::Document


462
463
464
# File 'lib/graphql/schema.rb', line 462

def to_document
  GraphQL::Language::DocumentFromSchemaDefinition.new(self).document
end

.to_json(**args) ⇒ Object

Returns the JSON response of Introspection::INTROSPECTION_QUERY. See as_json Return a Hash representation of the schema

Returns

  • String

:call-seq:

to_json(**args) -> String


405
406
407
# File 'lib/graphql/schema.rb', line 405

def to_json(**args)
  JSON.pretty_generate(as_json(**args))
end

.trace_class(new_class = nil) ⇒ Object



290
291
292
293
294
295
296
297
298
299
300
# File 'lib/graphql/schema.rb', line 290

def trace_class(new_class = nil)
  if new_class
    # If any modules were already added for `:default`,
    # re-apply them here
    mods = trace_modules_for(:default)
    mods.each { |mod| new_class.include(mod) }
    new_class.include(DefaultTraceClass)
    trace_mode(:default, new_class)
  end
  trace_class_for(:default, build: true)
end

.trace_class_for(mode, build: false) ⇒ Object

Returns

  • Class — Return the trace class to use for this mode, looking one up on the superclass if this Schema doesn't have one defined.

:call-seq:

trace_class_for(mode, build:) -> Class


308
309
310
311
312
313
314
315
316
317
318
# File 'lib/graphql/schema.rb', line 308

def trace_class_for(mode, build: false)
  if (trace_class = own_trace_modes[mode])
    trace_class
  elsif superclass.respond_to?(:trace_class_for) && (trace_class = superclass.trace_class_for(mode, build: false))
    trace_class
  elsif build
    own_trace_modes[mode] = build_trace_mode(mode)
  else
    nil
  end
end

.trace_mode(mode_name, trace_class) ⇒ Object

Configure trace_class to be used whenever context: { trace_mode: mode_name } is requested. default_trace_mode is used when no trace_mode: ... is requested.

When a trace_class is added this way, it will not receive other modules added with trace_with(...) unless trace_mode is explicitly given. (This class will not receive any default trace modules.)

Subclasses of the schema will use trace_class as a base class for this mode and those subclass also will not receive default tracing modules.

Parameters

  • mode_name (Symbol)
  • trace_class (Class) — subclass of GraphQL::Tracing::Trace

Returns

  • Object — void

:call-seq:

trace_mode(Symbol mode_name, Class trace_class) -> Object


340
341
342
343
# File 'lib/graphql/schema.rb', line 340

def trace_mode(mode_name, trace_class)
  own_trace_modes[mode_name] = trace_class
  nil
end

.trace_modules_for(trace_mode) ⇒ Object

Returns

  • Array<Module> — Modules added for tracing in trace_mode, including inherited ones

:call-seq:

trace_modules_for(trace_mode) -> Array[Module]


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

def trace_modules_for(trace_mode)
  modules = own_trace_modules[trace_mode]
  if superclass.respond_to?(:trace_modules_for)
    modules += superclass.trace_modules_for(trace_mode)
  end
  modules
end

.trace_options_for(mode) ⇒ Object

The options hash for this trace mode

Returns

  • Hash

:call-seq:

trace_options_for(mode) -> Hash


1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
# File 'lib/graphql/schema.rb', line 1960

def trace_options_for(mode)
  @trace_options_for_mode ||= {}
  @trace_options_for_mode[mode] ||= begin
    # It may be time to create an options hash for a mode that wasn't registered yet.
    # Mix in the default options in that case.
    default_options = mode == :default ? EMPTY_HASH : trace_options_for(:default)
    # Make sure this returns a new object so that other hashes aren't modified later
    if superclass.respond_to?(:trace_options_for)
      superclass.trace_options_for(mode).merge(default_options)
    else
      default_options.dup
    end
  end
end

.trace_with(trace_mod, mode: :default, **options) ⇒ Object

Mix trace_mod into this schema's Trace class so that its methods will be called at runtime.

You can attach a module to run in only some circumstances by using mode:. When a module is added with mode:, it will only run for queries with a matching context[:trace_mode].

Any custom trace modes also include the default trace_with ... modules (that is, those added without any particular mode: ... configuration).

See GraphQL::Tracing::Trace for available tracing methods.

Examples

Example: Adding a trace in a special mode

# only runs when `query.context[:trace_mode]` is `:special`
trace_with SpecialTrace, mode: :special

Parameters

  • trace_mod (Module) — A module that implements tracing methods
  • mode (Symbol) — Trace module will only be used for this trade mode
  • options (Hash) — Keywords that will be passed to the tracing class during #initialize

Returns

  • void

:call-seq:

trace_with(Module trace_mod, Symbol mode:, Hash **options) -> void


1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
# File 'lib/graphql/schema.rb', line 1924

def trace_with(trace_mod, mode: :default, **options)
  if mode.is_a?(Array)
    mode.each { |m| trace_with(trace_mod, mode: m, **options) }
  else
    tc = own_trace_modes[mode] ||= build_trace_mode(mode)
    tc.include(trace_mod)
    own_trace_modules[mode] << trace_mod
    add_trace_options_for(mode, options)
    if mode == :default
      # This module is being added as a default tracer. If any other mode classes
      # have already been created, but get their default behavior from a superclass,
      # Then mix this into this schema's subclass.
      # (But don't mix it into mode classes that aren't default-based.)
      own_trace_modes.each do |other_mode_name, other_mode_class|
        if other_mode_class < DefaultTraceClass
          # Don't add it back to the inheritance tree if it's already there
          if !(other_mode_class < trace_mod)
            other_mode_class.include(trace_mod)
          end
          # Add any options so they'll be available
          add_trace_options_for(other_mode_name, options)
        end
      end
    end
  end
  nil
end

.tracer(new_tracer, silence_deprecation_warning: false) ⇒ Object



1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
# File 'lib/graphql/schema.rb', line 1868

def tracer(new_tracer, silence_deprecation_warning: false)
  if !silence_deprecation_warning
    warn("`Schema.tracer(#{new_tracer.inspect})` is deprecated; use module-based `trace_with` instead. See: https://graphql-ruby.org/queries/tracing.html")
    warn "  #{caller(1, 1).first}"
  end
  default_trace = trace_class_for(:default, build: true)
  if default_trace.nil? || !(default_trace < GraphQL::Tracing::CallLegacyTracers)
    trace_with(GraphQL::Tracing::CallLegacyTracers)
  end

  own_tracers << new_tracer
end

.tracers ⇒ Object



1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
# File 'lib/graphql/schema.rb', line 1881

def tracers
  inherited = find_inherited_value(:tracers, EMPTY_ARRAY)
  if inherited.length > 0
    if own_tracers.length > 0
      inherited + own_tracers
    else
      inherited
    end
  else
    own_tracers
  end
end

.type_error(type_error, context) ⇒ Object

Called at runtime when GraphQL-Ruby encounters a mismatch between the application behavior and the GraphQL type system.

The default implementation of this method is to follow the GraphQL specification, but you can override this to report errors to your bug tracker or customize error handling.

Parameters

  • type_error (GraphQL::Error) — several specific error classes are passed here, see the default implementation for details
  • context (GraphQL::Query::Context) — the context for the currently-running operation

Returns

  • void

Raises

  • GraphQL::ExecutionError — to return this error to the client
  • GraphQL::Error — to crash the query and raise a developer-facing error

:call-seq:

type_error(GraphQL::Error type_error, GraphQL::Query::Context context) -> void | GraphQL::ExecutionError | GraphQL::Error


1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
# File 'lib/graphql/schema.rb', line 1738

def type_error(type_error, context)
  case type_error
  when GraphQL::InvalidNullError
    execution_error = GraphQL::ExecutionError.new(type_error.message, ast_nodes: type_error.ast_nodes)
    execution_error.path = type_error.path || context[:current_path]

    context.errors << execution_error
    execution_error
  when GraphQL::UnresolvedTypeError, GraphQL::StringEncodingError, GraphQL::FloatEncodingError, GraphQL::IntegerEncodingError
    raise type_error
  when GraphQL::FloatDecodingError, GraphQL::IntegerDecodingError
    nil
  end
end

.type_from_ast(ast_node, context: self.query_class.new(self, "{ __typename }").context) ⇒ Object



959
960
961
# File 'lib/graphql/schema.rb', line 959

def type_from_ast(ast_node, context: self.query_class.new(self, "{ __typename }").context)
  GraphQL::Schema::TypeExpression.build_type(context.query.types, ast_node)
end

.types(context = null_context) ⇒ Object

Build a map of { name => type } and return it. get_type is more efficient for finding one type by name, because it doesn't merge hashes.

Returns

  • Hash<String => Class> — A dictionary of type classes by their GraphQL name

:call-seq:

types(context) -> Hash[String, Class]


534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
# File 'lib/graphql/schema.rb', line 534

def types(context = null_context)
  if use_visibility_profile?
    types = Visibility::Profile.from_context(context, self)
    return types.all_types_h
  end
  all_types = non_introspection_types.merge(introspection_system.types)
  visible_types = {}
  all_types.each do |k, v|
    visible_types[k] =if v.is_a?(Array)
      visible_t = nil
      v.each do |t|
        if t.visible?(context)
          if visible_t.nil?
            visible_t = t
          else
            raise DuplicateNamesError.new(
              duplicated_name: k, duplicated_definition_1: visible_t.inspect, duplicated_definition_2: t.inspect
            )
          end
        end
      end
      visible_t
    else
      v
    end
  end
  visible_types
end

.unauthorized_field(unauthorized_error) ⇒ Object

This hook is called when a field fails an authorized? check.

By default, this hook implements the same behavior as unauthorized_object.

Whatever value is returned from this method will be used instead of the unauthorized field . If an error is raised, then nil will be used.

If you want to add an error to the "errors" key, raise a GraphQL::ExecutionError in this hook.

Parameters

  • unauthorized_error (GraphQL::UnauthorizedFieldError)

Returns

  • Field — The returned field will be put in the GraphQL response

:call-seq:

unauthorized_field(GraphQL::UnauthorizedFieldError unauthorized_error) -> Field


1712
1713
1714
# File 'lib/graphql/schema.rb', line 1712

def unauthorized_field(unauthorized_error)
  unauthorized_object(unauthorized_error)
end

.unauthorized_object(unauthorized_error) ⇒ Object

This hook is called when an object fails an authorized? check. You might report to your bug tracker here, so you can correct the field resolvers not to return unauthorized objects.

By default, this hook just replaces the unauthorized object with nil.

Whatever value is returned from this method will be used instead of the unauthorized object (accessible as unauthorized_error.object). If an error is raised, then nil will be used.

If you want to add an error to the "errors" key, raise a GraphQL::ExecutionError in this hook.

Parameters

  • unauthorized_error (GraphQL::UnauthorizedError)

Returns

  • Object — The returned object will be put in the GraphQL response

:call-seq:

unauthorized_object(GraphQL::UnauthorizedError unauthorized_error) -> Object


1688
1689
1690
# File 'lib/graphql/schema.rb', line 1688

def unauthorized_object(unauthorized_error)
  nil
end

.union_memberships(type = nil) ⇒ Object



916
917
918
919
920
921
922
923
924
925
926
927
928
929
# File 'lib/graphql/schema.rb', line 916

def union_memberships(type = nil)
  if type
    own_um = own_union_memberships.fetch(type.graphql_name, EMPTY_ARRAY)
    inherited_um = find_inherited_value(:union_memberships, EMPTY_HASH).fetch(type.graphql_name, EMPTY_ARRAY)
    own_um + inherited_um
  else
    joined_um = own_union_memberships.transform_values(&:dup)
    find_inherited_value(:union_memberships, EMPTY_HASH).each do |k, v|
      um = joined_um[k] ||= []
      um.concat(v)
    end
    joined_um
  end
end

.use(plugin, **kwargs) ⇒ Object

Add plugin to this schema

Parameters

  • plugin (#use) — A Schema plugin

Returns

  • Object — void

:call-seq:

use(#use plugin, **kwargs) -> Object


506
507
508
509
510
511
512
513
# File 'lib/graphql/schema.rb', line 506

def use(plugin, **kwargs)
  if !kwargs.empty?
    plugin.use(self, **kwargs)
  else
    plugin.use(self)
  end
  own_plugins << [plugin, kwargs]
end

.use_visibility_profile? ⇒ Boolean

:nodoc:

Returns:

  • (Boolean)


857
858
859
860
861
862
863
864
865
# File 'lib/graphql/schema.rb', line 857

def use_visibility_profile? # :nodoc:
  if defined?(@use_visibility_profile)
    @use_visibility_profile
  elsif superclass.respond_to?(:use_visibility_profile?)
    superclass.use_visibility_profile?
  else
    false
  end
end

.validate(string_or_document, rules: nil, context: nil) ⇒ Object

Validate a query string according to this schema.

Parameters

  • string_or_document (String, GraphQL::Language::Nodes::Document)

Returns

  • Array<GraphQL::StaticValidation::Error >

:call-seq:

validate(String | GraphQL::Language::Nodes::Document string_or_document, rules:, context:) -> Array[GraphQL::StaticValidation::Error]


1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
# File 'lib/graphql/schema.rb', line 1143

def validate(string_or_document, rules: nil, context: nil)
  doc = if string_or_document.is_a?(String)
    GraphQL.parse(string_or_document, max_tokens: max_query_string_tokens)
  else
    string_or_document
  end
  query = query_class.new(self, document: doc, context: context)
  validator_opts = { schema: self }
  rules && (validator_opts[:rules] = rules)
  validator = GraphQL::StaticValidation::Validator.new(**validator_opts)
  res = validator.validate(query, timeout: validate_timeout, max_errors: validate_max_errors)
  res[:errors]
end

.visible?(member, ctx) ⇒ Boolean

Returns:

  • (Boolean)


1648
1649
1650
# File 'lib/graphql/schema.rb', line 1648

def visible?(member, ctx)
  member.visible?(ctx)
end