forked from rmosolgo/graphql-ruby
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathschema.rb
More file actions
1983 lines (1755 loc) · 71.4 KB
/
schema.rb
File metadata and controls
1983 lines (1755 loc) · 71.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
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
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
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
999
1000
# frozen_string_literal: true
require "graphql/schema/base_64_encoder"
require "graphql/schema/catchall_middleware"
require "graphql/schema/default_parse_error"
require "graphql/schema/default_type_error"
require "graphql/schema/find_inherited_value"
require "graphql/schema/finder"
require "graphql/schema/invalid_type_error"
require "graphql/schema/introspection_system"
require "graphql/schema/late_bound_type"
require "graphql/schema/middleware_chain"
require "graphql/schema/null_mask"
require "graphql/schema/possible_types"
require "graphql/schema/rescue_middleware"
require "graphql/schema/timeout"
require "graphql/schema/timeout_middleware"
require "graphql/schema/traversal"
require "graphql/schema/type_expression"
require "graphql/schema/unique_within_type"
require "graphql/schema/validation"
require "graphql/schema/warden"
require "graphql/schema/build_from_definition"
require "graphql/schema/member"
require "graphql/schema/wrapper"
require "graphql/schema/list"
require "graphql/schema/non_null"
require "graphql/schema/argument"
require "graphql/schema/enum_value"
require "graphql/schema/enum"
require "graphql/schema/field_extension"
require "graphql/schema/field"
require "graphql/schema/input_object"
require "graphql/schema/interface"
require "graphql/schema/scalar"
require "graphql/schema/object"
require "graphql/schema/union"
require "graphql/schema/directive"
require "graphql/schema/directive/deprecated"
require "graphql/schema/directive/include"
require "graphql/schema/directive/skip"
require "graphql/schema/directive/feature"
require "graphql/schema/directive/transform"
require "graphql/schema/type_membership"
require "graphql/schema/resolver"
require "graphql/schema/mutation"
require "graphql/schema/relay_classic_mutation"
require "graphql/schema/subscription"
module GraphQL
# 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})
#
# Schemas can specify how queries should be executed against them.
# `query_execution_strategy`, `mutation_execution_strategy` and `subscription_execution_strategy`
# each apply to corresponding root types.
# #
# @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
#
class Schema
extend Forwardable
extend GraphQL::Schema::Member::AcceptsDefinition
extend GraphQL::Schema::Member::HasAstNode
include GraphQL::Define::InstanceDefinable
extend GraphQL::Schema::FindInheritedValue
class DuplicateTypeNamesError < GraphQL::Error
def initialize(type_name:, first_definition:, second_definition:, path:)
super("Multiple definitions for `#{type_name}`. Previously found #{first_definition.inspect} (#{first_definition.class}), then found #{second_definition.inspect} (#{second_definition.class}) at #{path.join(".")}")
end
end
class UnresolvedLateBoundTypeError < GraphQL::Error
attr_reader :type
def initialize(type:)
@type = type
super("Late bound type was never found: #{type.inspect}")
end
end
module LazyHandlingMethods
# 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`)
# @api private
def after_lazy(value, &block)
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
# Override this method to handle lazy objects in a custom way.
# @param value [Object] an instance of a class registered with {.lazy_resolve}
# @return [Object] A GraphQL-ready (non-lazy) object
# @api private
def sync_lazy(value)
lazy_method = lazy_method_name(value)
if lazy_method
synced_value = value.public_send(lazy_method)
sync_lazy(synced_value)
else
value
end
end
# @return [Symbol, nil] The method name to lazily resolve `obj`, or nil if `obj`'s class wasn't registered with {#lazy_resolve}.
def lazy_method_name(obj)
lazy_methods.get(obj)
end
# @return [Boolean] True if this object should be lazily resolved
def lazy?(obj)
!!lazy_method_name(obj)
end
# Return a lazy if any of `maybe_lazies` are lazy,
# otherwise, call the block eagerly and return the result.
# @param maybe_lazies [Array]
# @api private
def after_any_lazies(maybe_lazies)
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
end
include LazyHandlingMethods
extend LazyHandlingMethods
accepts_definitions \
:query_execution_strategy, :mutation_execution_strategy, :subscription_execution_strategy,
:max_depth, :max_complexity, :default_max_page_size,
:orphan_types, :resolve_type, :type_error, :parse_error,
:error_bubbling,
:raise_definition_error,
:object_from_id, :id_from_object,
:default_mask,
:cursor_encoder,
# If these are given as classes, normalize them. Accept `nil` when building from string.
query: ->(schema, t) { schema.query = t.respond_to?(:graphql_definition) ? t.graphql_definition : t },
mutation: ->(schema, t) { schema.mutation = t.respond_to?(:graphql_definition) ? t.graphql_definition : t },
subscription: ->(schema, t) { schema.subscription = t.respond_to?(:graphql_definition) ? t.graphql_definition : t },
disable_introspection_entry_points: ->(schema) { schema.disable_introspection_entry_points = true },
disable_schema_introspection_entry_point: ->(schema) { schema.disable_schema_introspection_entry_point = true },
disable_type_introspection_entry_point: ->(schema) { schema.disable_type_introspection_entry_point = true },
directives: ->(schema, directives) { schema.directives = directives.reduce({}) { |m, d| m[d.graphql_name] = d; m } },
directive: ->(schema, directive) { schema.directives[directive.graphql_name] = directive },
instrument: ->(schema, type, instrumenter, after_built_ins: false) {
if type == :field && after_built_ins
type = :field_after_built_ins
end
schema.instrumenters[type] << instrumenter
},
query_analyzer: ->(schema, analyzer) {
if analyzer == GraphQL::Authorization::Analyzer
warn("The Authorization query analyzer is deprecated. Authorizing at query runtime is generally a better idea.")
end
schema.query_analyzers << analyzer
},
multiplex_analyzer: ->(schema, analyzer) { schema.multiplex_analyzers << analyzer },
middleware: ->(schema, middleware) { schema.middleware << middleware },
lazy_resolve: ->(schema, lazy_class, lazy_value_method) { schema.lazy_methods.set(lazy_class, lazy_value_method) },
rescue_from: ->(schema, err_class, &block) { schema.rescue_from(err_class, &block) },
tracer: ->(schema, tracer) { schema.tracers.push(tracer) }
ensure_defined :introspection_system
attr_accessor \
:query, :mutation, :subscription,
:query_execution_strategy, :mutation_execution_strategy, :subscription_execution_strategy,
:max_depth, :max_complexity, :default_max_page_size,
:orphan_types, :directives,
:query_analyzers, :multiplex_analyzers, :instrumenters, :lazy_methods,
:cursor_encoder,
:ast_node,
:raise_definition_error,
:introspection_namespace,
:analysis_engine
# [Boolean] True if this object bubbles validation errors up from a field into its parent InputObject, if there is one.
attr_accessor :error_bubbling
# Single, long-lived instance of the provided subscriptions class, if there is one.
# @return [GraphQL::Subscriptions]
attr_accessor :subscriptions
# @return [MiddlewareChain] MiddlewareChain which is applied to fields during execution
attr_accessor :middleware
# @return [<#call(member, ctx)>] A callable for filtering members of the schema
# @see {Query.new} for query-specific filters with `except:`
attr_accessor :default_mask
# @see {GraphQL::Query::Context} The parent class of these classes
# @return [Class] Instantiated for each query
attr_accessor :context_class
# [Boolean] True if this object disables the introspection entry point fields
attr_accessor :disable_introspection_entry_points
def disable_introspection_entry_points?
!!@disable_introspection_entry_points
end
# [Boolean] True if this object disables the __schema introspection entry point field
attr_accessor :disable_schema_introspection_entry_point
def disable_schema_introspection_entry_point?
!!@disable_schema_introspection_entry_point
end
# [Boolean] True if this object disables the __type introspection entry point field
attr_accessor :disable_type_introspection_entry_point
def disable_type_introspection_entry_point?
!!@disable_type_introspection_entry_point
end
class << self
attr_writer :default_execution_strategy
end
def default_filter
GraphQL::Filter.new(except: default_mask)
end
# @return [Array<#trace(key, data)>] Tracers applied to every query
# @see {Query#tracers} for query-specific tracers
attr_reader :tracers
DYNAMIC_FIELDS = ["__type", "__typename", "__schema"].freeze
attr_reader :static_validator, :object_from_id_proc, :id_from_object_proc, :resolve_type_proc
def initialize
@tracers = []
@definition_error = nil
@orphan_types = []
@directives = {}
self.class.default_directives.each do |name, dir|
@directives[name] = dir.graphql_definition
end
@static_validator = GraphQL::StaticValidation::Validator.new(schema: self)
@middleware = MiddlewareChain.new(final_step: GraphQL::Execution::Execute::FieldResolveStep)
@query_analyzers = []
@multiplex_analyzers = []
@resolve_type_proc = nil
@object_from_id_proc = nil
@id_from_object_proc = nil
@type_error_proc = DefaultTypeError
@parse_error_proc = DefaultParseError
@instrumenters = Hash.new { |h, k| h[k] = [] }
@lazy_methods = GraphQL::Execution::Lazy::LazyMethodMap.new
@lazy_methods.set(GraphQL::Execution::Lazy, :value)
@cursor_encoder = Base64Encoder
# Default to the built-in execution strategy:
@analysis_engine = GraphQL::Analysis
@query_execution_strategy = self.class.default_execution_strategy
@mutation_execution_strategy = self.class.default_execution_strategy
@subscription_execution_strategy = self.class.default_execution_strategy
@default_mask = GraphQL::Schema::NullMask
@rebuilding_artifacts = false
@context_class = GraphQL::Query::Context
@introspection_namespace = nil
@introspection_system = nil
@interpreter = false
@error_bubbling = false
@disable_introspection_entry_points = false
@disable_schema_introspection_entry_point = false
@disable_type_introspection_entry_point = false
end
# @return [Boolean] True if using the new {GraphQL::Execution::Interpreter}
def interpreter?
@interpreter
end
# @api private
attr_writer :interpreter
def inspect
"#<#{self.class.name} ...>"
end
def initialize_copy(other)
super
@orphan_types = other.orphan_types.dup
@directives = other.directives.dup
@static_validator = GraphQL::StaticValidation::Validator.new(schema: self)
@middleware = other.middleware.dup
@query_analyzers = other.query_analyzers.dup
@multiplex_analyzers = other.multiplex_analyzers.dup
@tracers = other.tracers.dup
@possible_types = GraphQL::Schema::PossibleTypes.new(self)
@lazy_methods = other.lazy_methods.dup
@instrumenters = Hash.new { |h, k| h[k] = [] }
other.instrumenters.each do |key, insts|
@instrumenters[key].concat(insts)
end
if other.rescues?
@rescue_middleware = other.rescue_middleware
end
# This will be rebuilt when it's requested
# or during a later `define` call
@types = nil
@introspection_system = nil
end
def rescue_from(*args, &block)
rescue_middleware.rescue_from(*args, &block)
end
def remove_handler(*args, &block)
rescue_middleware.remove_handler(*args, &block)
end
def using_ast_analysis?
@analysis_engine == GraphQL::Analysis::AST
end
# For forwards-compatibility with Schema classes
alias :graphql_definition :itself
# Validate a query string according to this schema.
# @param string_or_document [String, GraphQL::Language::Nodes::Document]
# @return [Array<GraphQL::StaticValidation::Error >]
def validate(string_or_document, rules: nil, context: nil)
doc = if string_or_document.is_a?(String)
GraphQL.parse(string_or_document)
else
string_or_document
end
query = GraphQL::Query.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)
res[:errors]
end
def define(**kwargs, &block)
super
ensure_defined
# Assert that all necessary configs are present:
validation_error = Validation.validate(self)
validation_error && raise(GraphQL::RequiredImplementationMissingError, validation_error)
rebuild_artifacts
@definition_error = nil
nil
rescue StandardError => err
if @raise_definition_error || err.is_a?(CyclicalDefinitionError) || err.is_a?(GraphQL::RequiredImplementationMissingError)
raise
else
# Raise this error _later_ to avoid messing with Rails constant loading
@definition_error = err
end
nil
end
# Attach `instrumenter` to this schema for instrumenting events of `instrumentation_type`.
# @param instrumentation_type [Symbol]
# @param instrumenter
# @return [void]
def instrument(instrumentation_type, instrumenter)
@instrumenters[instrumentation_type] << instrumenter
if instrumentation_type == :field
rebuild_artifacts
end
end
# @return [Array<GraphQL::BaseType>] The root types of this schema
def root_types
@root_types ||= begin
rebuild_artifacts
@root_types
end
end
# @see [GraphQL::Schema::Warden] Restricted access to members of a schema
# @return [GraphQL::Schema::TypeMap] `{ name => type }` pairs of types in this schema
def types
@types ||= begin
rebuild_artifacts
@types
end
end
def get_type(type_name)
@types[type_name]
end
# @api private
def introspection_system
@introspection_system ||= begin
rebuild_artifacts
@introspection_system
end
end
# Returns a list of Arguments and Fields referencing a certain type
# @param type_name [String]
# @return [Hash]
def references_to(type_name = nil)
rebuild_artifacts unless defined?(@type_reference_map)
if type_name
@type_reference_map.fetch(type_name, [])
else
@type_reference_map
end
end
# Returns a list of Union types in which a type is a member
# @param type [GraphQL::ObjectType]
# @return [Array<GraphQL::UnionType>] list of union types of which the type is a member
def union_memberships(type)
rebuild_artifacts unless defined?(@union_memberships)
@union_memberships.fetch(type.name, [])
end
# Execute a query on itself. Raises an error if the schema definition is invalid.
# @see {Query#initialize} for arguments.
# @return [Hash] query result, ready to be serialized as JSON
def execute(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],
}
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
# Execute several queries on itself. Raises an error if the schema definition is invalid.
# @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],
# }
#
# @see {Query#initialize} for query keyword arguments
# @see {Execution::Multiplex#run_queries} for multiplex keyword arguments
# @param queries [Array<Hash>] Keyword arguments for each query
# @param context [Hash] Multiplex-level context
# @return [Array<Hash>] One result for each query in the input
def multiplex(queries, **kwargs)
with_definition_error_check {
GraphQL::Execution::Multiplex.run_all(self, queries, **kwargs)
}
end
# Search for a schema member using a string path
# @example Finding a Field
# Schema.find("Ensemble.musicians")
#
# @see {GraphQL::Schema::Finder} for more examples
# @param path [String] A dot-separated path to the member
# @raise [Schema::Finder::MemberNotFoundError] if path could not be found
# @return [GraphQL::BaseType, GraphQL::Field, GraphQL::Argument, GraphQL::Directive] A GraphQL Schema Member
def find(path)
rebuild_artifacts unless defined?(@finder)
@find_cache[path] ||= @finder.find(path)
end
# Resolve field named `field_name` for type `parent_type`.
# Handles dynamic fields `__typename`, `__type` and `__schema`, too
# @param parent_type [String, GraphQL::BaseType]
# @param field_name [String]
# @return [GraphQL::Field, nil] The field named `field_name` on `parent_type`
# @see [GraphQL::Schema::Warden] Restricted access to members of a schema
def get_field(parent_type, field_name)
with_definition_error_check do
parent_type_name = case parent_type
when GraphQL::BaseType, Class, Module
parent_type.graphql_name
when String
parent_type
else
raise "Unexpected parent_type: #{parent_type}"
end
defined_field = @instrumented_field_map[parent_type_name][field_name]
if defined_field
defined_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
end
# Fields for this type, after instrumentation is applied
# @return [Hash<String, GraphQL::Field>]
def get_fields(type)
@instrumented_field_map[type.graphql_name]
end
def type_from_ast(ast_node, context:)
GraphQL::Schema::TypeExpression.build_type(self, ast_node)
end
# @see [GraphQL::Schema::Warden] Restricted access to members of a schema
# @param type_defn [GraphQL::InterfaceType, GraphQL::UnionType] the type whose members you want to retrieve
# @param context [GraphQL::Query::Context] The context for the current query
# @return [Array<GraphQL::ObjectType>] types which belong to `type_defn` in this schema
def possible_types(type_defn, context = GraphQL::Query::NullContext)
if context == GraphQL::Query::NullContext
@possible_types ||= GraphQL::Schema::PossibleTypes.new(self)
@possible_types.possible_types(type_defn, context)
else
# Use the incoming context to cache this instance --
# if it were cached on the schema, we'd have a memory leak
# https://github.com/rmosolgo/graphql-ruby/issues/2878
ns = context.namespace(:possible_types)
per_query_possible_types = ns[:possible_types] ||= GraphQL::Schema::PossibleTypes.new(self)
per_query_possible_types.possible_types(type_defn, context)
end
end
# @see [GraphQL::Schema::Warden] Resticted access to root types
# @return [GraphQL::ObjectType, nil]
def root_type_for_operation(operation)
case operation
when "query"
query
when "mutation"
mutation
when "subscription"
subscription
else
raise ArgumentError, "unknown operation type: #{operation}"
end
end
def execution_strategy_for_operation(operation)
case operation
when "query"
query_execution_strategy
when "mutation"
mutation_execution_strategy
when "subscription"
subscription_execution_strategy
else
raise ArgumentError, "unknown operation type: #{operation}"
end
end
# Determine the GraphQL type for a given object.
# This is required for unions and interfaces (including Relay's `Node` interface)
# @see [GraphQL::Schema::Warden] Restricted access to members of a schema
# @param type [GraphQL::UnionType, GraphQL:InterfaceType] the abstract type which is being resolved
# @param object [Any] An application object which GraphQL is currently resolving on
# @param ctx [GraphQL::Query::Context] The context for the current query
# @return [GraphQL::ObjectType] The type for exposing `object` in GraphQL
def resolve_type(type, object, ctx = :__undefined__)
check_resolved_type(type, object, ctx) do |ok_type, ok_object, ok_ctx|
if @resolve_type_proc.nil?
raise(GraphQL::RequiredImplementationMissingError, "Can't determine GraphQL type for: #{ok_object.inspect}, define `resolve_type (type, obj, ctx) -> { ... }` inside `Schema.define`.")
end
@resolve_type_proc.call(ok_type, ok_object, ok_ctx)
end
end
# This is a compatibility hack so that instance-level and class-level
# methods can get correctness checks without calling one another
# @api private
def check_resolved_type(type, object, ctx = :__undefined__)
if ctx == :__undefined__
# Old method signature
ctx = object
object = type
type = nil
end
if object.is_a?(GraphQL::Schema::Object)
object = object.object
end
if type.respond_to?(:graphql_definition)
type = type.graphql_definition
end
# Prefer a type-local function; fall back to the schema-level function
type_proc = type && type.resolve_type_proc
type_result = if type_proc
type_proc.call(object, ctx)
else
yield(type, object, ctx)
end
if type_result.nil?
nil
else
after_lazy(type_result) do |resolved_type_result|
if resolved_type_result.respond_to?(:graphql_definition)
resolved_type_result = resolved_type_result.graphql_definition
end
if !resolved_type_result.is_a?(GraphQL::BaseType)
type_str = "#{resolved_type_result} (#{resolved_type_result.class.name})"
raise "resolve_type(#{object}) returned #{type_str}, but it should return a GraphQL type"
else
resolved_type_result
end
end
end
end
def resolve_type=(new_resolve_type_proc)
callable = GraphQL::BackwardsCompatibility.wrap_arity(new_resolve_type_proc, from: 2, to: 3, last: true, name: "Schema#resolve_type(type, obj, ctx)")
@resolve_type_proc = callable
end
# Fetch an application object by its unique id
# @param id [String] A unique identifier, provided previously by this GraphQL schema
# @param ctx [GraphQL::Query::Context] The context for the current query
# @return [Any] The application object identified by `id`
def object_from_id(id, ctx)
if @object_from_id_proc.nil?
raise(GraphQL::RequiredImplementationMissingError, "Can't fetch an object for id \"#{id}\" because the schema's `object_from_id (id, ctx) -> { ... }` function is not defined")
else
@object_from_id_proc.call(id, ctx)
end
end
# @param new_proc [#call] A new callable for fetching objects by ID
def object_from_id=(new_proc)
@object_from_id_proc = new_proc
end
# When we encounter a type error during query execution, we call this hook.
#
# You can use this hook to write a log entry,
# add a {GraphQL::ExecutionError} to the response (with `ctx.add_error`)
# or raise an exception and halt query execution.
#
# @example A `nil` is encountered by a non-null field
# type_error ->(err, query_ctx) {
# err.is_a?(GraphQL::InvalidNullError) # => true
# }
#
# @example An object doesn't resolve to one of a {UnionType}'s members
# type_error ->(err, query_ctx) {
# err.is_a?(GraphQL::UnresolvedTypeError) # => true
# }
#
# @see {DefaultTypeError} is the default behavior.
# @param err [GraphQL::TypeError] The error encountered during execution
# @param ctx [GraphQL::Query::Context] The context for the field where the error occurred
# @return void
def type_error(err, ctx)
@type_error_proc.call(err, ctx)
end
# @param new_proc [#call] A new callable for handling type errors during execution
def type_error=(new_proc)
@type_error_proc = new_proc
end
# Can't delegate to `class`
alias :_schema_class :class
def_delegators :_schema_class, :unauthorized_object, :unauthorized_field, :inaccessible_fields
def_delegators :_schema_class, :directive
def_delegators :_schema_class, :error_handler
# Given this schema member, find the class-based definition object
# whose `method_name` should be treated as an application hook
# @see {.visible?}
# @see {.accessible?}
def call_on_type_class(member, method_name, context, default:)
member = if member.respond_to?(:type_class)
member.type_class
else
member
end
if member.respond_to?(:relay_node_type) && (t = member.relay_node_type)
member = t
end
if member.respond_to?(method_name)
member.public_send(method_name, context)
else
default
end
end
def visible?(member, context)
call_on_type_class(member, :visible?, context, default: true)
end
def accessible?(member, context)
call_on_type_class(member, :accessible?, context, default: true)
end
# A function to call when {#execute} receives an invalid query string
#
# @see {DefaultParseError} is the default behavior.
# @param err [GraphQL::ParseError] The error encountered during parsing
# @param ctx [GraphQL::Query::Context] The context for the query where the error occurred
# @return void
def parse_error(err, ctx)
@parse_error_proc.call(err, ctx)
end
# @param new_proc [#call] A new callable for handling parse errors during execution
def parse_error=(new_proc)
@parse_error_proc = new_proc
end
# Get a unique identifier from this object
# @param object [Any] An application object
# @param type [GraphQL::BaseType] The current type definition
# @param ctx [GraphQL::Query::Context] the context for the current query
# @return [String] a unique identifier for `object` which clients can use to refetch it
def id_from_object(object, type, ctx)
if @id_from_object_proc.nil?
raise(GraphQL::RequiredImplementationMissingError, "Can't generate an ID for #{object.inspect} of type #{type}, schema's `id_from_object` must be defined")
else
@id_from_object_proc.call(object, type, ctx)
end
end
# @param new_proc [#call] A new callable for generating unique IDs
def id_from_object=(new_proc)
@id_from_object_proc = new_proc
end
# Create schema with the result of an introspection query.
# @param introspection_result [Hash] A response from {GraphQL::Introspection::INTROSPECTION_QUERY}
# @return [GraphQL::Schema] the schema described by `input`
def self.from_introspection(introspection_result)
GraphQL::Schema::Loader.load(introspection_result)
end
# Create schema from an IDL schema or file containing an IDL definition.
# @param definition_or_path [String] A schema definition string, or a path to a file containing the definition
# @param default_resolve [<#call(type, field, obj, args, ctx)>] A callable for handling field resolution
# @param parser [Object] An object for handling definition string parsing (must respond to `parse`)
# @param using [Hash] Plugins to attach to the created schema with `use(key, value)`
# @param interpreter [Boolean] If false, the legacy {Execution::Execute} runtime will be used
# @return [Class] the schema described by `document`
def self.from_definition(definition_or_path, default_resolve: nil, interpreter: true, parser: BuildFromDefinition::DefaultParser, using: {})
# If the file ends in `.graphql`, treat it like a filepath
definition = if definition_or_path.end_with?(".graphql")
File.read(definition_or_path)
else
definition_or_path
end
GraphQL::Schema::BuildFromDefinition.from_definition(
definition,
default_resolve: default_resolve,
parser: parser,
using: using,
interpreter: interpreter,
)
end
# Error that is raised when [#Schema#from_definition] is passed an invalid schema definition string.
class InvalidDocumentError < Error; end;
# Return the GraphQL IDL for the schema
# @param context [Hash]
# @param only [<#call(member, ctx)>]
# @param except [<#call(member, ctx)>]
# @return [String]
def to_definition(only: nil, except: nil, context: {})
GraphQL::Schema::Printer.print_schema(self, only: only, except: except, context: context)
end
# Return the GraphQL::Language::Document IDL AST for the schema
# @param context [Hash]
# @param only [<#call(member, ctx)>]
# @param except [<#call(member, ctx)>]
# @return [GraphQL::Language::Document]
def to_document(only: nil, except: nil, context: {})
GraphQL::Language::DocumentFromSchemaDefinition.new(self, only: only, except: except, context: context).document
end
# Return the Hash response of {Introspection::INTROSPECTION_QUERY}.
# @param context [Hash]
# @param only [<#call(member, ctx)>]
# @param except [<#call(member, ctx)>]
# @return [Hash] GraphQL result
def as_json(only: nil, except: nil, context: {})
execute(Introspection.query(include_deprecated_args: true), only: only, except: except, context: context).to_h
end
# Returns the JSON response of {Introspection::INTROSPECTION_QUERY}.
# @see {#as_json}
# @return [String]
def to_json(*args)
JSON.pretty_generate(as_json(*args))
end
def new_connections?
!!connections
end
attr_accessor :connections
class << self
extend Forwardable
# For compatibility, these methods all:
# - Cause the Schema instance to be created, if it hasn't been created yet
# - Delegate to that instance
# Eventually, the methods will be moved into this class, removing the need for the singleton.
def_delegators :graphql_definition,
# Execution
:execution_strategy_for_operation,
:validate,
# Configuration
:metadata, :redefine,
:id_from_object_proc, :object_from_id_proc,
:id_from_object=, :object_from_id=,
:remove_handler
# @return [GraphQL::Subscriptions]
attr_accessor :subscriptions
# Returns the JSON response of {Introspection::INTROSPECTION_QUERY}.
# @see {#as_json}
# @return [String]
def to_json(**args)
JSON.pretty_generate(as_json(**args))
end
# Return the Hash response of {Introspection::INTROSPECTION_QUERY}.
# @param context [Hash]
# @param only [<#call(member, ctx)>]
# @param except [<#call(member, ctx)>]
# @return [Hash] GraphQL result
def as_json(only: nil, except: nil, context: {})
execute(Introspection.query(include_deprecated_args: true), only: only, except: except, context: context).to_h
end
# Return the GraphQL IDL for the schema
# @param context [Hash]
# @param only [<#call(member, ctx)>]
# @param except [<#call(member, ctx)>]
# @return [String]
def to_definition(only: nil, except: nil, context: {})
GraphQL::Schema::Printer.print_schema(self, only: only, except: except, context: context)
end
# Return the GraphQL::Language::Document IDL AST for the schema
# @return [GraphQL::Language::Document]
def to_document
GraphQL::Language::DocumentFromSchemaDefinition.new(self).document
end
def find(path)
if !@finder
@find_cache = {}
@finder ||= GraphQL::Schema::Finder.new(self)
end
@find_cache[path] ||= @finder.find(path)
end
def graphql_definition
@graphql_definition ||= to_graphql
end
def default_filter
GraphQL::Filter.new(except: default_mask)
end
def default_mask(new_mask = nil)
if new_mask
@own_default_mask = new_mask
else
@own_default_mask || find_inherited_value(:default_mask, Schema::NullMask)
end
end
def static_validator
GraphQL::StaticValidation::Validator.new(schema: self)
end
def use(plugin, **kwargs)
if kwargs.any?
plugin.use(self, **kwargs)
else
plugin.use(self)
end
own_plugins << [plugin, kwargs]
end
def plugins
find_inherited_value(:plugins, EMPTY_ARRAY) + own_plugins
end
def to_graphql
schema_defn = self.new
schema_defn.raise_definition_error = true
schema_defn.query = query && query.graphql_definition
schema_defn.mutation = mutation && mutation.graphql_definition
schema_defn.subscription = subscription && subscription.graphql_definition
schema_defn.max_complexity = max_complexity
schema_defn.error_bubbling = error_bubbling
schema_defn.max_depth = max_depth
schema_defn.default_max_page_size = default_max_page_size
schema_defn.orphan_types = orphan_types.map(&:graphql_definition)
schema_defn.disable_introspection_entry_points = disable_introspection_entry_points?
schema_defn.disable_schema_introspection_entry_point = disable_schema_introspection_entry_point?
schema_defn.disable_type_introspection_entry_point = disable_type_introspection_entry_point?
prepped_dirs = {}
directives.each { |k, v| prepped_dirs[k] = v.graphql_definition}
schema_defn.directives = prepped_dirs
schema_defn.introspection_namespace = introspection
schema_defn.resolve_type = method(:resolve_type)
schema_defn.object_from_id = method(:object_from_id)
schema_defn.id_from_object = method(:id_from_object)
schema_defn.type_error = method(:type_error)
schema_defn.context_class = context_class
schema_defn.cursor_encoder = cursor_encoder
schema_defn.tracers.concat(tracers)
schema_defn.query_analyzers.concat(query_analyzers)
schema_defn.analysis_engine = analysis_engine
schema_defn.middleware.concat(all_middleware)
schema_defn.multiplex_analyzers.concat(multiplex_analyzers)
schema_defn.query_execution_strategy = query_execution_strategy
schema_defn.mutation_execution_strategy = mutation_execution_strategy
schema_defn.subscription_execution_strategy = subscription_execution_strategy
schema_defn.default_mask = default_mask
instrumenters.each do |step, insts|
insts.each do |inst|
schema_defn.instrumenters[step] << inst
end
end
lazy_methods.each do |lazy_class, value_method|
schema_defn.lazy_methods.set(lazy_class, value_method)
end
rescues.each do |err_class, handler|
schema_defn.rescue_from(err_class, &handler)
end
schema_defn.subscriptions ||= self.subscriptions
if !schema_defn.interpreter?
schema_defn.instrumenters[:query] << GraphQL::Schema::Member::Instrumentation
end
if new_connections?
schema_defn.connections = self.connections
end