/
schema.rb
1190 lines (1051 loc) · 40.5 KB
/
schema.rb
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/addition"
require "graphql/schema/base_64_encoder"
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/null_mask"
require "graphql/schema/timeout"
require "graphql/schema/type_expression"
require "graphql/schema/unique_within_type"
require "graphql/schema/warden"
require "graphql/schema/build_from_definition"
require "graphql/schema/validator"
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/flagged"
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 GraphQL::Schema::Member::HasAstNode
extend GraphQL::Schema::FindInheritedValue
class DuplicateNamesError < GraphQL::Error
attr_reader :duplicated_name
def initialize(duplicated_name:, duplicated_definition_1:, duplicated_definition_2:)
@duplicated_name = duplicated_name
super(
"Found two visible definitions for `#{duplicated_name}`: #{duplicated_definition_1}, #{duplicated_definition_2}"
)
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
# Error that is raised when [#Schema#from_definition] is passed an invalid schema definition string.
class InvalidDocumentError < Error; end;
class << self
# Create schema with the result of an introspection query.
# @param introspection_result [Hash] A response from {GraphQL::Introspection::INTROSPECTION_QUERY}
# @return [Class<GraphQL::Schema>] the schema described by `input`
def 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)`
# @return [Class] the schema described by `document`
def from_definition(definition_or_path, default_resolve: nil, parser: GraphQL.default_parser, using: {})
# If the file ends in `.graphql`, treat it like a filepath
if definition_or_path.end_with?(".graphql")
GraphQL::Schema::BuildFromDefinition.from_definition_path(
definition_or_path,
default_resolve: default_resolve,
parser: parser,
using: using,
)
else
GraphQL::Schema::BuildFromDefinition.from_definition(
definition_or_path,
default_resolve: default_resolve,
parser: parser,
using: using,
)
end
end
def deprecated_graphql_definition
graphql_definition(silence_deprecation_warning: true)
end
# @return [GraphQL::Subscriptions]
def subscriptions(inherited: true)
defined?(@subscriptions) ? @subscriptions : (inherited ? find_inherited_value(:subscriptions, nil) : nil)
end
def subscriptions=(new_implementation)
@subscriptions = new_implementation
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
# 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
# @return [String, nil]
def description(new_description = nil)
if new_description
@description = new_description
elsif defined?(@description)
@description
else
find_inherited_value(:description, nil)
end
end
def find(path)
if !@finder
@find_cache = {}
@finder ||= GraphQL::Schema::Finder.new(self)
end
@find_cache[path] ||= @finder.find(path)
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
# Build a map of `{ name => type }` and return it
# @return [Hash<String => Class>] A dictionary of type classes by their GraphQL name
# @see get_type Which is more efficient for finding _one type_ by name, because it doesn't merge hashes.
def types(context = GraphQL::Query::NullContext)
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
# @param type_name [String]
# @return [Module, nil] A type, or nil if there's no type called `type_name`
def get_type(type_name, context = GraphQL::Query::NullContext)
local_entry = own_types[type_name]
type_defn = case local_entry
when nil
nil
when Array
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
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) : nil)
end
# @api private
attr_writer :connections
# @return [GraphQL::Pagination::Connections] if installed
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
def new_connections?
!!connections
end
def query(new_query_object = nil)
if new_query_object
if @query_object
raise GraphQL::Error, "Second definition of `query(...)` (#{new_query_object.inspect}) is invalid, already configured with #{@query_object.inspect}"
else
@query_object = new_query_object
add_type_and_traverse(new_query_object, root: true)
nil
end
else
@query_object || find_inherited_value(:query)
end
end
def mutation(new_mutation_object = nil)
if new_mutation_object
if @mutation_object
raise GraphQL::Error, "Second definition of `mutation(...)` (#{new_mutation_object.inspect}) is invalid, already configured with #{@mutation_object.inspect}"
else
@mutation_object = new_mutation_object
add_type_and_traverse(new_mutation_object, root: true)
nil
end
else
@mutation_object || find_inherited_value(:mutation)
end
end
def subscription(new_subscription_object = nil)
if new_subscription_object
if @subscription_object
raise GraphQL::Error, "Second definition of `subscription(...)` (#{new_subscription_object.inspect}) is invalid, already configured with #{@subscription_object.inspect}"
else
@subscription_object = new_subscription_object
add_subscription_extension_if_necessary
add_type_and_traverse(new_subscription_object, root: true)
nil
end
else
@subscription_object || find_inherited_value(:subscription)
end
end
# @see [GraphQL::Schema::Warden] Restricted 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 root_types
@root_types
end
# @param type [Module] The type definition whose possible types you want to see
# @return [Hash<String, Module>] All possible types, if no `type` is given.
# @return [Array<Module>] Possible types for `type`, if it's given.
def possible_types(type = nil, context = GraphQL::Query::NullContext)
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.graphql_name]
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.graphql_name] ||
(
superclass.respond_to?(:possible_types) ?
superclass.possible_types(type, context) :
EMPTY_ARRAY
)
end
else
find_inherited_value(:possible_types, EMPTY_HASH)
.merge(own_possible_types)
.merge(introspection_system.possible_types)
end
end
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.dup
find_inherited_value(:union_memberhips, EMPTY_HASH).each do |k, v|
um = joined_um[k] ||= []
um.concat(v)
end
joined_um
end
end
# @api private
# @see GraphQL::Dataloader
def dataloader_class
@dataloader_class || GraphQL::Dataloader::NullDataloader
end
attr_writer :dataloader_class
def references_to(to_type = nil, from: nil)
@own_references_to ||= Hash.new { |h, k| h[k] = [] }
if to_type
if !to_type.is_a?(String)
to_type = to_type.graphql_name
end
if from
@own_references_to[to_type] << from
else
own_refs = @own_references_to[to_type]
inherited_refs = find_inherited_value(:references_to, EMPTY_HASH)[to_type] || EMPTY_ARRAY
own_refs + inherited_refs
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.any?
inherited_value.merge(@own_references_to)
else
@own_references_to
end
end
end
def type_from_ast(ast_node, context: nil)
type_owner = context ? context.warden : self
GraphQL::Schema::TypeExpression.build_type(type_owner, ast_node)
end
def get_field(type_or_name, field_name, context = GraphQL::Query::NullContext)
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
def get_fields(type, context = GraphQL::Query::NullContext)
type.fields(context)
end
def introspection(new_introspection_namespace = nil)
if new_introspection_namespace
@introspection = new_introspection_namespace
# reset this cached value:
@introspection_system = nil
else
@introspection || find_inherited_value(:introspection)
end
end
def introspection_system
if !@introspection_system
@introspection_system = Schema::IntrospectionSystem.new(self)
@introspection_system.resolve_late_bindings
end
@introspection_system
end
def cursor_encoder(new_encoder = nil)
if new_encoder
@cursor_encoder = new_encoder
end
@cursor_encoder || find_inherited_value(:cursor_encoder, Base64Encoder)
end
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
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
def query_execution_strategy(new_query_execution_strategy = nil)
if new_query_execution_strategy
@query_execution_strategy = new_query_execution_strategy
else
@query_execution_strategy || find_inherited_value(:query_execution_strategy, self.default_execution_strategy)
end
end
def mutation_execution_strategy(new_mutation_execution_strategy = nil)
if new_mutation_execution_strategy
@mutation_execution_strategy = new_mutation_execution_strategy
else
@mutation_execution_strategy || find_inherited_value(:mutation_execution_strategy, self.default_execution_strategy)
end
end
def subscription_execution_strategy(new_subscription_execution_strategy = nil)
if new_subscription_execution_strategy
@subscription_execution_strategy = new_subscription_execution_strategy
else
@subscription_execution_strategy || find_inherited_value(:subscription_execution_strategy, self.default_execution_strategy)
end
end
attr_writer :validate_timeout
def validate_timeout(new_validate_timeout = nil)
if new_validate_timeout
@validate_timeout = new_validate_timeout
elsif defined?(@validate_timeout)
@validate_timeout
else
find_inherited_value(:validate_timeout)
end
end
# 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, timeout: validate_timeout, max_errors: validate_max_errors)
res[:errors]
end
attr_writer :validate_max_errors
def validate_max_errors(new_validate_max_errors = nil)
if new_validate_max_errors
@validate_max_errors = new_validate_max_errors
elsif defined?(@validate_max_errors)
@validate_max_errors
else
find_inherited_value(:validate_max_errors)
end
end
attr_writer :max_complexity
def max_complexity(max_complexity = nil)
if max_complexity
@max_complexity = max_complexity
elsif defined?(@max_complexity)
@max_complexity
else
find_inherited_value(:max_complexity)
end
end
attr_writer :analysis_engine
def analysis_engine
@analysis_engine || find_inherited_value(:analysis_engine, self.default_analysis_engine)
end
def using_ast_analysis?
true
end
def interpreter?
true
end
attr_writer :interpreter
def error_bubbling(new_error_bubbling = nil)
if !new_error_bubbling.nil?
@error_bubbling = new_error_bubbling
else
@error_bubbling.nil? ? find_inherited_value(:error_bubbling) : @error_bubbling
end
end
attr_writer :error_bubbling
attr_writer :max_depth
def max_depth(new_max_depth = nil)
if new_max_depth
@max_depth = new_max_depth
elsif defined?(@max_depth)
@max_depth
else
find_inherited_value(:max_depth)
end
end
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
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
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
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
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
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
def orphan_types(*new_orphan_types)
if new_orphan_types.any?
new_orphan_types = new_orphan_types.flatten
add_type_and_traverse(new_orphan_types, root: false)
own_orphan_types.concat(new_orphan_types.flatten)
end
find_inherited_value(:orphan_types, EMPTY_ARRAY) + own_orphan_types
end
def default_execution_strategy
if superclass <= GraphQL::Schema
superclass.default_execution_strategy
else
@default_execution_strategy ||= GraphQL::Execution::Interpreter
end
end
def default_analysis_engine
if superclass <= GraphQL::Schema
superclass.default_analysis_engine
else
@default_analysis_engine ||= GraphQL::Analysis::AST
end
end
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
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
NEW_HANDLER_HASH = ->(h, k) {
h[k] = {
class: k,
handler: nil,
subclass_handlers: Hash.new(&NEW_HANDLER_HASH),
}
}
def error_handlers
@error_handlers ||= {
class: nil,
handler: nil,
subclass_handlers: Hash.new(&NEW_HANDLER_HASH),
}
end
# @api private
def handle_or_reraise(context, err)
handler = Execution::Errors.find_handler_for(self, err.class)
if handler
runtime_info = context.namespace(:interpreter) || {}
obj = runtime_info[:current_object]
args = runtime_info[:current_arguments]
args = args && args.keyword_arguments
field = runtime_info[:current_field]
if obj.is_a?(GraphQL::Schema::Object)
obj = obj.object
end
handler[:handler].call(err, obj, args, context, field)
else
raise err
end
end
# rubocop:disable Lint/DuplicateMethods
module ResolveTypeWithType
def resolve_type(type, obj, ctx)
maybe_lazy_resolve_type_result = if type.is_a?(Module) && type.respond_to?(:resolve_type)
type.resolve_type(obj, ctx)
else
super
end
after_lazy(maybe_lazy_resolve_type_result) do |resolve_type_result|
if resolve_type_result.is_a?(Array) && resolve_type_result.size == 2
resolved_type = resolve_type_result[0]
resolved_value = resolve_type_result[1]
else
resolved_type = resolve_type_result
resolved_value = obj
end
if resolved_type.nil? || (resolved_type.is_a?(Module) && resolved_type.respond_to?(:kind))
if resolved_value
[resolved_type, resolved_value]
else
resolved_type
end
else
raise ".resolve_type should return a type definition, but got #{resolved_type.inspect} (#{resolved_type.class}) from `resolve_type(#{type}, #{obj}, #{ctx})`"
end
end
end
end
def resolve_type(type, obj, ctx)
if type.kind.object?
type
else
raise GraphQL::RequiredImplementationMissingError, "#{self.name}.resolve_type(type, obj, ctx) must be implemented to use Union types or Interface types (tried to resolve: #{type.name})"
end
end
# rubocop:enable Lint/DuplicateMethods
def inherited(child_class)
if self == GraphQL::Schema
child_class.directives(default_directives.values)
end
child_class.singleton_class.prepend(ResolveTypeWithType)
super
end
def object_from_id(node_id, ctx)
raise GraphQL::RequiredImplementationMissingError, "#{self.name}.object_from_id(node_id, ctx) must be implemented to load by ID (tried to load from id `#{node_id}`)"
end
def id_from_object(object, type, ctx)
raise GraphQL::RequiredImplementationMissingError, "#{self.name}.id_from_object(object, type, ctx) must be implemented to create global ids (tried to create an id for `#{object.inspect}`)"
end
def visible?(member, ctx)
member.visible?(ctx)
end
def accessible?(member, ctx)
member.accessible?(ctx)
end
# This hook is called when a client tries to access one or more
# fields that fail the `accessible?` check.
#
# By default, an error is added to the response. Override this hook to
# track metrics or return a different error to the client.
#
# @param error [InaccessibleFieldsError] The analysis error for this check
# @return [AnalysisError, nil] Return an error to skip the query
def inaccessible_fields(error)
error
end
# 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.
#
# @param unauthorized_error [GraphQL::UnauthorizedError]
# @return [Object] The returned object will be put in the GraphQL response
def unauthorized_object(unauthorized_error)
nil
end
# 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.
#
# @param unauthorized_error [GraphQL::UnauthorizedFieldError]
# @return [Field] The returned field will be put in the GraphQL response
def unauthorized_field(unauthorized_error)
unauthorized_object(unauthorized_error)
end
def type_error(type_error, ctx)
case type_error
when GraphQL::InvalidNullError
ctx.errors << type_error
when GraphQL::UnresolvedTypeError, GraphQL::StringEncodingError, GraphQL::IntegerEncodingError
raise type_error
when GraphQL::IntegerDecodingError
nil
end
end
# A function to call when {#execute} receives an invalid query string
#
# The default is to add the error to `context.errors`
# @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(parse_err, ctx)
ctx.errors.push(parse_err)
end
def lazy_resolve(lazy_class, value_method)
lazy_methods.set(lazy_class, value_method)
end
def instrument(instrument_step, instrumenter, options = {})
own_instrumenters[instrument_step] << instrumenter
end
# Add several directives at once
# @param new_directives [Class]
def directives(*new_directives)
if new_directives.any?
new_directives.flatten.each { |d| directive(d) }
end
find_inherited_value(:directives, default_directives).merge(own_directives)
end
# Attach a single directive to this schema
# @param new_directive [Class]
# @return void
def directive(new_directive)
add_type_and_traverse(new_directive, root: false)
end
def default_directives
@default_directives ||= {
"include" => GraphQL::Schema::Directive::Include,
"skip" => GraphQL::Schema::Directive::Skip,
"deprecated" => GraphQL::Schema::Directive::Deprecated,
}.freeze
end
def tracer(new_tracer)
own_tracers << new_tracer
end
def tracers
find_inherited_value(:tracers, EMPTY_ARRAY) + own_tracers
end
def query_analyzer(new_analyzer)
own_query_analyzers << new_analyzer
end
def query_analyzers
find_inherited_value(:query_analyzers, EMPTY_ARRAY) + own_query_analyzers
end
def multiplex_analyzer(new_analyzer)
own_multiplex_analyzers << new_analyzer
end
def multiplex_analyzers
find_inherited_value(:multiplex_analyzers, EMPTY_ARRAY) + own_multiplex_analyzers
end
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
# Execute a query on itself.
# @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],
dataloader: ctx[:dataloader],
}
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, concurrently.
#
# @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_all} 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)
GraphQL::Execution::Multiplex.run_all(self, queries, **kwargs)
end
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