-
Notifications
You must be signed in to change notification settings - Fork 162
/
schema.clj
1788 lines (1508 loc) · 72.1 KB
/
schema.clj
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
; Copyright (c) 2017-present Walmart, Inc.
;
; Licensed under the Apache License, Version 2.0 (the "License")
; you may not use this file except in compliance with the License.
; You may obtain a copy of the License at
;
; http://www.apache.org/licenses/LICENSE-2.0
;
; Unless required by applicable law or agreed to in writing, software
; distributed under the License is distributed on an "AS IS" BASIS,
; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
; See the License for the specific language governing permissions and
; limitations under the License.
(ns com.walmartlabs.lacinia.schema
"Responsible for constructing and validating the GraphQL schema.
GraphQL schema starts in a format easy to read and maintain as an EDN file.
Compiling the schema performs a number of validations and reorganizations to
make query execution faster and simpler, such as generating a flatter structure for the
schema, and pre-computing many defaults."
(:refer-clojure :exclude [compile])
(:require
[clojure.spec.alpha :as s]
[com.walmartlabs.lacinia.introspection :as introspection]
[com.walmartlabs.lacinia.internal-utils
:refer [map-vals map-kvs filter-vals deep-merge q
is-internal-type-name? sequential-or-set? as-keyword
cond-let ->TaggedValue is-tagged-value? extract-value extract-type-tag
to-message qualified-name aggregate-results]]
[com.walmartlabs.lacinia.resolve :as resolve
:refer [ResolverResult resolve-as is-resolver-result?]]
[clojure.string :as str]
[clojure.set :refer [difference]]
[clojure.pprint :as pprint]
[com.walmartlabs.lacinia.selection :as selection]
[com.walmartlabs.lacinia.selector-context :as sc])
(:import
(clojure.lang IObj)
(java.io Writer)))
;; When using Clojure 1.8, the dependency on clojure-future-spec must be included,
;; and this code will trigger
(when (-> *clojure-version* :minor (< 9))
(require '[clojure.future :refer [any? simple-keyword? simple-symbol?]]))
(defrecord CompiledSchema [])
(defn ^:no-doc compiled-schema?
[m]
(instance? CompiledSchema m))
;;-------------------------------------------------------------------------------
;; ## Helpers
(def ^:private graphql-identifier #"(?ix) _* [a-z] [a-z0-9_]*")
(defrecord ^:private CoercionFailure
[message])
(defn coercion-failure
"Returns a special record that indicates a failure coercing a scalar value.
This may be returned from a scalar's :parse or :serialize callback.
This is deprecated in version 0.32.0; just throw an exception instead.
A coercion failure includes a message key, and may also include additional data.
message
: A message string presentable to a user.
data
: An optional map of additional details about the failure."
{:added "0.16.0"
:deprecated "0.32.0"}
([message]
(coercion-failure message nil))
([message data]
(merge (->CoercionFailure message) data)))
(defn is-coercion-failure?
"Is this a coercion error created by [[coercion-failure]]?"
{:added "0.16.0"}
[v]
(instance? CoercionFailure v))
(defn ^:private map-types
"Maps the types of the schema that match the provided category, but leaves
the rest unchanged."
[schema category f]
(reduce-kv (fn [s k v]
(if (-> v :category (= category))
(assoc s k (f v))
s))
schema
schema))
(defn tag-with-type
"Tags a value with a GraphQL type name, a keyword.
The keyword should identify a specific concrete object
(not an interface or union) in the relevent schema.
In most cases, this is accomplished by modifying the value's metadata.
For the more rare case, where a particular type is used rather than a Clojure
map, this function returns a new wrapper instance that combines the value and the type name."
[x type-name]
(cond
;; IObj is the base interface for things that can vary their metadata:
(instance? IObj x)
(vary-meta x assoc ::type-name type-name)
;; From here on is the edge case where a fixed type is used that doesn't
;; support metadata.
;; In some cases, the resolver for a field may tag a value even though it
;; gets re-tagged automatically.
(is-tagged-value? x)
(if (= type-name (extract-type-tag x))
x
(->TaggedValue (extract-value x) type-name))
:else
(->TaggedValue x type-name)))
(defn ^:no-doc type-map
"Reduces a compiled schema to a list of categories and the names of types in that category, useful
for exception reporting."
[schema]
(->> schema
vals
(filter :type-name) ;; ::schema/root has no :type-name
(group-by :category)
(map-vals #(->> (map :type-name %)
(remove is-internal-type-name?)
sort
vec))
;; The above may remove entire categories, drop the keys when
;; all the values have been filtered out.
(filter-vals seq)))
(defn as-conformer
"Creates a clojure.spec/conformer as a wrapper around the supplied function.
The function is only invoked if the value to be conformed is non-nil.
Any exception thrown by the function is silently caught and the returned conformer
will return :clojure.spec/invalid or a [[coercion-failure]].
This function has been deprecated, as Scalar parse and serialize callbacks are now
simple functions, and not conformers."
{:deprecated "0.31.0"}
[f]
(s/conformer
(fn [x]
(try
(when (some? x)
(f x))
(catch Exception e
(if-some [message (.getMessage e)]
(coercion-failure message (ex-data e))
::s/invalid))))))
(defn ^:private parse-int
[v]
;; The serialized is a little more forgiving about converting non-integers to integers.
;; On the parse side, we're a little more picky.
(when (integer? v)
(if (<= Integer/MIN_VALUE v Integer/MAX_VALUE)
(int v)
(coercion-failure "Int value outside of allowed 32 bit integer range." {:value (pr-str v)}))))
(defn ^:private serialize-int
[v]
(cond
(integer? v)
(if (<= Integer/MIN_VALUE v Integer/MAX_VALUE)
(int v)
(coercion-failure "Int value outside of allowed 32 bit integer range." {:value (pr-str v)}))
;; Per spec; floats are allowed only if they are a whole number.
(float? v)
(when (= v (Math/floor (double v)))
(let [long-v (long v)]
(if (<= Integer/MIN_VALUE long-v Integer/MAX_VALUE)
(int long-v)
(coercion-failure "Int value outside of allowed 32 bit integer range." {:value (pr-str v)}))))))
(defn ^:private parse-float
[v]
(cond
(instance? Double v)
v
;; Spec: should coerce non-floating-point raw values as result coercion and for input coercion
(number? v)
(double v)))
(defn ^:private seralize-float
[v]
(cond
(instance? Double v)
v
(number? v)
(double v)
(string? v)
(try
;; Per the spec, if a string can be parsed to a double, that's allowed
(Double/parseDouble v)
(catch Throwable _
nil))))
(defn ^:private parse-boolean
[v]
(when
(instance? Boolean v)
v))
(defn ^:private parse-id
[v]
(cond
(string? v)
v
(integer? v)
(str v)))
(defn ^:private serialize-id
[v]
;; Although the spec discusses serializing the ID type "as appropriate", that would be a case
;; of overriding this default implementation.
(when (string? v)
v))
(defn ^:private parse-string
[v]
(when (string? v)
v))
(def default-scalar-transformers
{:String {:parse parse-string
:serialize str}
:Float {:parse parse-float
:serialize seralize-float}
:Int {:parse parse-int
:serialize serialize-int}
:Boolean {:parse parse-boolean
:serialize parse-boolean}
:ID {:parse parse-id
:serialize serialize-id}})
(defn ^:private error
([message]
(error message nil))
([message data]
(merge {:message message} data)))
;;-------------------------------------------------------------------------------
;; ## Validations
(s/def ::deprecated (s/or :basic true?
:detailed string?))
(s/def ::schema-key (s/and simple-keyword?
::graphql-identifier))
(s/def ::graphql-identifier #(re-matches graphql-identifier (name %)))
;; For style and/or historical reasons, type names can be a keyword or a symbol.
;; The convention is that built-in types use a symbol, and application-defined types
;; use a keyword.
(s/def ::type-name (s/and
(s/nonconforming
(s/or :keyword simple-keyword?
:symbol simple-symbol?))
::graphql-identifier))
(s/def ::type (s/or :base-type ::type-name
:wrapped-type ::wrapped-type))
(s/def ::wrapped-type (s/cat :modifier ::wrapped-type-modifier
:type ::type))
;; Use of a function here, rather than just the set, is due to https://github.com/bhb/expound/issues/101
(s/def ::wrapped-type-modifier #(contains? #{'list 'non-null} %))
(s/def ::arg (s/keys :req-un [::type]
:opt-un [::description
::directives
::default-value]))
(s/def ::default-value any?)
(s/def ::args (s/map-of ::schema-key ::arg))
;; Defining these callbacks in spec has been a challenge. At some point,
;; we can expand this to capture a bit more about what a field resolver
;; is passed and should return.
(s/def ::resolve (s/or :function ::function-or-var
:protocol ::resolver-type))
(s/def ::resolver-type #(satisfies? resolve/FieldResolver %))
(s/def ::field (s/keys :opt-un [::description
::resolve
::args
::directives
::deprecated]
:req-un [::type]))
(s/def ::operation (s/keys :opt-un [::description
::deprecated
::args]
:req-un [::type
::resolve]))
(s/def ::fields (s/map-of ::schema-key ::field))
(s/def ::implements (s/and (s/coll-of ::type-name)
seq))
(s/def ::description string?)
(s/def ::directives (s/coll-of ::directive))
(s/def ::directive (s/keys :req-un [::directive-type]
:opt-un [::directive-args]))
(s/def ::directive-type ::schema-key)
(s/def ::directive-args (s/map-of keyword? any?))
(s/def ::tag (s/or
:symbol symbol?
:class class?))
(s/def ::object (s/keys :req-un [::fields]
:opt-un [::implements
::directives
::description
::tag]))
;; Here we'd prefer a version of ::fields where :resolve was not defined.
(s/def ::interface (s/keys :opt-un [::description
::directives
::fields]))
;; A list of keyword identifying objects that are part of a union.
(s/def ::members (s/and (s/coll-of ::type-name)
seq))
(s/def ::union (s/keys :opt-un [::description
::directives]
:req-un [::members]))
(s/def ::enum-value (s/and (s/nonconforming
(s/or :string string?
:keyword simple-keyword?
:symbol simple-symbol?))
::graphql-identifier))
(s/def ::enum-value-def (s/or :bare-value ::enum-value
:described (s/keys :req-un [::enum-value]
:opt-un [::description
::deprecated
::directives])))
(s/def ::values (s/and (s/coll-of ::enum-value-def) seq))
;; Regrettably, :parse and :serialize on ::enum could reasonably be maps, but
;; that can't be easily expressed here (unless we create a :enum/parse and :enum/serialize).
;; We'll go there if there's a need for it.
(s/def ::enum (s/keys :opt-un [::description
::parse
::serialize
::directives]
:req-un [::values]))
;; The type of an input object field is more constrained than an ordinary field, but that is
;; handled with compile-time checks. Input objects should not have a :resolve or :args as well.
;; Defining an input-object in terms of :properties (with a corresponding ::properties and ::property spec)
;; may be more correct, but it's a big change.
(s/def ::input-object (s/keys :opt-un [::description
::directives]
:req-un [::fields]))
;; Prior to 0.31.0, specs were conformers.
;; With the breaking change in 0.31.0, we want to make sure that custom scalars
;; have been updated.
(s/def ::not-a-conformer #(not (s/spec? %)))
(s/def ::parse-or-serialize-fn (s/and ::not-a-conformer
::function-or-var))
(s/def ::function-or-var (s/or :function fn?
:var var?))
(s/def ::parse ::parse-or-serialize-fn)
(s/def ::serialize ::parse-or-serialize-fn)
(s/def ::scalar (s/keys :opt-un [::description
::directives]
:req-un [::parse
::serialize]))
(s/def ::scalars (s/map-of ::schema-key ::scalar))
(s/def ::interfaces (s/map-of ::schema-key ::interface))
(s/def ::objects (s/map-of ::schema-key ::object))
(s/def ::input-objects (s/map-of ::schema-key ::input-object))
(s/def ::enums (s/map-of ::schema-key ::enum))
(s/def ::unions (s/map-of ::schema-key ::union))
(s/def ::context (s/nilable map?))
;; These are the argument values passed to a resolver or streamer;
;; as opposed to ::args which are argument definitions.
(s/def ::arguments (s/nilable (s/map-of ::schema-key any?)))
;; Same issue as with ::resolve.
(s/def ::stream ::function-or-var)
(s/def ::queries (s/map-of ::schema-key ::operation))
(s/def ::mutations (s/map-of ::schema-key ::operation))
(s/def ::subscription (s/keys :opt-un [::description
::resolve
::args]
:req-un [::type
::stream]))
(s/def ::subscriptions (s/map-of ::schema-key ::subscription))
(s/def ::directive-defs (s/map-of ::schema-key ::directive-def))
(s/def ::directive-def (s/keys :opt-un [::description
::args]
:req-un [::locations]))
(s/def ::locations (s/coll-of ::location))
(s/def ::location #{:query :mutation :subscription
:field :fragment-definition :fragment-spread :inline-fragment
:schema :scalar :object
:field-definition :argument-definition :interface
:union :enum :enum-value :input-object :input-field-definition})
(s/def ::roots (s/map-of #{:query :mutation :subscription} ::schema-key))
(s/def ::schema-object
(s/keys :opt-un [::scalars
::interfaces
::objects
::input-objects
::enums
::unions
::roots
::queries
::mutations
::subscriptions
;; Schema-level directives
::directives
::directive-defs]))
;; Again, this can be fleshed out once we have a handle on defining specs for
;; functions:
(s/def ::default-field-resolver ::function-or-var)
(s/def ::promote-nils-to-empty-list? boolean?)
(s/def ::enable-introspection? boolean?)
(s/def ::compile-options (s/keys :opt-un [::default-field-resolver
::promote-nils-to-empty-list?
::enable-introspection?]))
(defrecord ^:private Directive [directive-type arguments effector arguments-extractor]
selection/Directive
(directive-type [_] directive-type)
selection/Arguments
(arguments [_] arguments))
(defrecord ^:private Type [category type-name description fields directives compiled-directives
implements tag]
selection/Type
(type-name [_] type-name)
(type-kind [_] :object)
selection/Fields
(fields [_] fields)
selection/Directives
(directives [_] compiled-directives))
(defn ^:no-doc root-type-name
"For a compiled field (or argument) definition, delves down through the :type tag to find
the root type name, a keyword."
[field-def]
;; In some error scenarios, the query references an unknown field and
;; the field-def is nil. Without this check, this loops endlessly.
(when field-def
(loop [type-def (:type field-def)]
(if (-> type-def :kind (= :root))
(:type type-def)
(recur (:type type-def))))))
(defrecord ^:private Field [type type-string directives compiled-directives
field-name qualified-name args null-collapser]
selection/Field
(root-type-name [_] (root-type-name type))
selection/QualifiedName
(qualified-name [_] qualified-name)
selection/Directives
(directives [_] compiled-directives))
(defrecord ^:private Interface [category type-name member fields directives compiled-directives]
selection/Type
(type-name [_] type-name)
(type-kind [_] :interface)
selection/Fields
(fields [_] fields)
selection/Directives
(directives [_] compiled-directives))
(defrecord ^:private Union [category type-name description directives compiled-directives]
selection/Type
(type-name [_] type-name)
(type-kind [_] :union)
selection/Directives
(directives [_] compiled-directives))
(defrecord ^:private EnumType [category type-name description parse serialize values
values-detail values-set
directives compiled-directives]
selection/Type
(type-name [_] type-name)
(type-kind [_] :enum)
selection/Directives
(directives [_] compiled-directives))
(defrecord ^:private Scalar [category type-name description parsae serialize directives compiled-directives]
selection/Type
(type-name [_] type-name)
(type-kind [_] :enum)
selection/Directives
(directives [_] compiled-directives))
(defn ^:private compile-directives
[element]
(let [{:keys [directives]} element]
(if (seq directives)
(assoc element :compiled-directives (->> directives
(map (fn [{:keys [directive-type directive-args]}]
(map->Directive
{:directive-type directive-type
:arguments directive-args})))
(group-by selection/directive-type)))
element)))
(defmulti ^:private check-compatible
"Given two type definitions, dispatches on a vector of the category of the two types.
'Returns true if the two types are compatible.
The interface defines the constraint type, the field defines the constrained type.
This is only invoked when the constraint type and constrained types are not equal.
The rules for this are in section 3.1.2.3 of the spec."
(fn [constraint-type constrained-type]
(mapv :category [constraint-type constrained-type])))
(defmethod check-compatible :default
[_ _]
;; Remember that for object-vs-object, scalar-vs-scalar, and
;; enum-vs-enum, we don't get this far if the types are the same.
;; For disparate types, generally not compatible (e.g., enum vs. scalar).
false)
(defmethod check-compatible [:union :object]
[i-type f-type]
(contains? (:members i-type) (:type-name f-type)))
(defmethod check-compatible [:interface :object]
[i-type f-type]
(contains? (:implements f-type) (:type-name i-type)))
;; That's as far as the spec goes, but one could imagine additonal rules
;; such as a union-vs-union (the field union must be a subset of the interface union),
;; or interface-union (all members of the union must implement the interface).
(defn ^:private is-compatible-type?
"Compares two field type maps (on from the interface, one from the object) for compatibility."
[schema interface-type object-type]
(let [i-kind (:kind interface-type)
o-kind (:kind object-type)
i-type (:type interface-type)
o-type (:type object-type)]
(cond
;; When the object field is non-null and the interface field allows nulls that's ok,
;; the object can be more specific than the interface.
(and (= o-kind :non-null)
(not= i-kind :non-null))
(recur schema i-kind o-type)
;; Otherwise :list must match :list, and :root must match :root,
;; and :non-null must match :non-null
(not= o-kind i-kind)
false
;; For :list and :non-null, they match, move down a level, towards :root
(#{:list :non-null} o-kind)
(recur schema i-type o-type)
;; Shortcut the compatible type check if the exact same type
(= i-type o-type)
true
:else
(check-compatible (get schema i-type)
(get schema o-type)))))
(defn ^:private is-assignable?
"Returns true if the object field is type compatible with the interface field."
[schema interface-field object-field]
(let [interface-type (:type interface-field)
object-type (:type object-field)]
(or (= interface-type object-type)
(is-compatible-type? schema interface-type object-type))))
;;-------------------------------------------------------------------------------
;; ## Types
(defn ^:private expand-type
"Compiles a type from the input schema to the format used in the
compiled schema."
;; TODO: This nested maps format works, but given the simple modifiers
;; we have, just converting from nested lists to a flattened vector
;; might work just as well. It would also make finding the root type
;; cheap: just use last.
[type]
(cond
(sequential? type)
(let [[modifier next-type & anything-else] type
kind (get {'list :list
'non-null :non-null} modifier)]
(when (or (nil? next-type)
(nil? kind)
(seq anything-else))
(throw (ex-info "Expected (list|non-null <type>)."
{:type type})))
{:kind kind
:type (expand-type next-type)})
;; By convention, symbols are used for pre-defined scalar types, and
;; keywords are used for user-defined types, interfaces, unions, enums, etc.
(or (keyword? type)
(symbol? type))
{:kind :root
:type (as-keyword type)}
:else
(throw (ex-info "Could not process type."
{:type type}))))
(defn ^:private type->string
"Converts the result of expand-type back into a string, as a type reference would appear in the
query language or SDL (e.g., `[String]!`)."
[input-type]
(let [{:keys [kind type]} input-type]
(case kind
:root (name type)
:list (str "[" (type->string type) "]")
:non-null (str (type->string type) "!"))))
(defn ^:private add-type-string
[field-definition]
(let [field-type (:type field-definition)
type-string (type->string field-type)]
(assoc field-definition :type-string type-string)))
(defn ^:private rewrite-type
"Rewrites the type tag of a field (or argument) into a nested structure of types.
types are maps with two keys, :kind and :type.
:kind may be :list, :non-null, or :root.
:type is a nested type map, or (for :root kind), the keyword name of a
schema type (a scalar, enum, object, etc.)."
[field]
(try
(update field :type expand-type)
(catch Throwable t
(throw (ex-info "Could not identify type of field."
{:field field}
t)))))
(defn ^:private compile-arg
"It's convinient to treat fields and arguments the same at this level."
[arg-name arg-def]
(-> arg-def
rewrite-type
(assoc :arg-name arg-name)))
(defn ^:private is-null?
[v]
(= v ::null))
(defn ^:private null-to-nil
[v]
(if (is-null? v) nil v))
(defn ^:private collapse-nulls-in-object
[forgive-null? map-type? value]
(cond
(nil? value)
value
(is-null? value)
(if forgive-null?
nil
::null)
(not map-type?)
value
(some is-null? (vals value))
(if forgive-null? nil ::null)
:else
(map-vals null-to-nil value)))
(defn ^:no-doc collapse-nulls-in-map
[m]
(collapse-nulls-in-object true true m))
(defn ^:private build-null-collapser
"Builds a null-collapser for a field definition; the null collapser transforms a resolved value
for the field, potentially to the value ::null if it is nil but non-nullable OR if any sub-selection
collapses to ::null.
A nullable field that contains a value of ::null collapses to nil.
For lists, a list that contains a ::null collapses down to either nil or ::null."
[schema forgive-null? type]
(let [{:keys [kind]
nested-type :type} type]
(case kind
:root
(let [element-def (get schema nested-type)
{:keys [category]} element-def
map-type? (contains? #{:union :object :interface} category)]
(fn [value]
(collapse-nulls-in-object forgive-null? map-type? value)))
:non-null
(let [nested-collapser (build-null-collapser schema false nested-type)]
(fn [value]
(let [value' (nested-collapser value)]
(if (nil? value')
::null
value'))))
:list
(let [nested-collapser (build-null-collapser schema true nested-type)
promote-nils-to-empty-list (get-in schema [::options :promote-nils-to-empty-list?])
empty-list (if promote-nils-to-empty-list [] nil)]
(fn [values]
(let [values' (when values
(map nested-collapser values))]
(cond
(nil? values')
empty-list
(some is-null? values')
(if forgive-null? empty-list ::null)
:else
values')))))))
(defn ^:private compile-field
"Rewrites the type of the field, and the type of any arguments."
[schema type-def field-name field-def]
(let [{:keys [type-name]} type-def
field-def' (-> field-def
map->Field
rewrite-type
add-type-string
compile-directives
(assoc :field-name field-name
:qualified-name (qualified-name type-name field-name))
(update :args #(map-kvs (fn [arg-name arg-def]
[arg-name (assoc (compile-arg arg-name arg-def)
:qualified-name (qualified-name type-name field-name arg-name))])
%)))
collapser (build-null-collapser schema true (:type field-def'))]
(assoc field-def' :null-collapser collapser)))
(defn ^:private wrap-resolver-to-ensure-resolver-result
[resolver]
(cond
;; The FieldResolver protocol allows a record (e.g., a component) to act as a field
;; resolver. This is where we turn it into a function. We can't tell whether
;; the method will return a ResolverResult or a bare value, so it will end up on
;; the less efficient path (the :else clause).
;; This also works with reify-ed instances of FieldResolver.
(satisfies? resolve/FieldResolver resolver)
(recur (resolve/as-resolver-fn resolver))
;; If a resolver reports its type as ResolverResult, then we don't
;; need to wrap it. This can really add up for all the default resolvers.
;; It's not so important for general resolvers.
(-> resolver meta :tag (identical? ResolverResult))
resolver
;; This is the "less efficient" path, as the result has to be tested to see
;; it is is a resolver result or not.
:else
(fn [context args value]
(let [raw-value (resolver context args value)
is-result? (is-resolver-result? raw-value)]
(if is-result?
raw-value
(resolve-as raw-value))))))
(defn ^:no-doc floor-selector
[selector-context]
(let [callback (:callback selector-context)]
(callback selector-context)))
(defn ^:private selector-error
[selector-context error]
(let [callback (:callback selector-context)]
(-> selector-context
(assoc
:resolved-value nil
:resolved-type nil)
(cond-> error (update :errors conj error))
callback)))
(defn ^:private create-root-selector
"Creates a selector function for the :root kind, which is the point at which
a type refers to something in the schema.
type - object definition containing the field
field - field definition
field-type-name - from the root :root kind "
[schema field-def field-type-name]
(let [field-type (get schema field-type-name)
_ (when (nil? field-type)
(throw (ex-info (format "Field %s references unknown type %s."
(-> field-def :qualified-name q)
(-> field-def :type q))
{:field field-def
:schema-types (type-map schema)})))
category (:category field-type)
;; Build up layers of checks and other logic and a series of chained selector functions.
;; Normally, don't redefine local symbols, but here it makes it easier to follow and less
;; brittle.
selector floor-selector
selector (if (= :scalar category)
(let [serializer (:serialize field-type)]
(fn select-coercion [selector-context]
(cond-let
:let [{:keys [resolved-value]} selector-context]
(nil? resolved-value)
(selector selector-context)
:let [serialized (try
(serializer resolved-value)
(catch Throwable t
(coercion-failure (to-message t) (ex-data t))))]
(nil? serialized)
(selector-error selector-context
(let [value-str (pr-str resolved-value)]
{:message (format "Unable to serialize %s as type %s."
value-str
(q field-type-name))
:value value-str
:type-name field-type-name}))
(is-coercion-failure? serialized)
(selector-error selector-context
(-> serialized
(update :message
#(str "Coercion error serializing value: " %))
(assoc :type-name field-type-name
:value (pr-str resolved-value))))
:else
(selector (assoc selector-context :resolved-value serialized)))))
selector)
selector (if (= :enum category)
(let [possible-values (-> field-type :values set)
serializer (:serialize field-type)]
(fn validate-enum [{:keys [resolved-value]
:as selector-context}]
(cond-let
;; The resolver function can return a value that makes sense from
;; the application's model (for example, a namespaced keyword or even a string)
;; and the enum's serializer converts that to a keyword, which is then
;; validated to match a known value for the enum.
(nil? resolved-value)
(selector selector-context)
:let [serialized (serializer resolved-value)]
(not (possible-values serialized))
(selector-error selector-context (error "Field resolver returned an undefined enum value."
{:resolved-value resolved-value
:serialized-value serialized
:enum-values possible-values}))
:else
(selector (assoc selector-context :resolved-value serialized)))))
selector)
union-or-interface? (#{:interface :union} category)
selector (if union-or-interface?
(let [member-types (:members field-type)]
(fn select-allowed-types [{:keys [resolved-type resolved-value]
:as selector-context}]
(cond
(or (nil? resolved-value)
(contains? member-types resolved-type))
(selector selector-context)
(nil? resolved-type)
(selector-error selector-context (error "Field resolver returned an instance not tagged with a schema type."))
:else
(selector-error selector-context (error "Value returned from resolver has incorrect type for field."
{:field-type field-type-name
:actual-type resolved-type
:allowed-types member-types})))))
selector)
type-map (when union-or-interface?
(let [member-types (:members field-type)
member-objects (map schema member-types)
type-map (reduce (fn [m {:keys [tag type-name]}]
(if tag
(assoc m tag type-name)
m))
{}
member-objects)]
(when (seq type-map)
type-map)))
selector (fn select-unwrap-tagged-type [selector-context]
(cond-let
;; Use explicitly tagged value (this usually applies to Java objects
;; that can't provide meta data).
:let [resolved-value (:resolved-value selector-context)]
(is-tagged-value? resolved-value)
(selector (assoc selector-context
:resolved-value (extract-value resolved-value)
:resolved-type (extract-type-tag resolved-value)))
;; Check for explicit meta-data:
:let [type-name (-> resolved-value meta ::type-name)]
(some? type-name)
(selector (assoc selector-context :resolved-type type-name))
;; Use, if available, the mapping from tag to object that might be provided
;; for some objects.
:let [resolved-type (when type-map
(->> resolved-value
class
(get type-map)))]
(some? resolved-type)
(selector (assoc selector-context :resolved-type resolved-type))
;; Let a later stage fail if it is a union or interface and there's no explicit
;; type.
:else
(selector selector-context)))
selector (if (#{:object :input-object} category)
(fn select-apply-static-type [selector-context]
;; TODO: Maybe a check that if the resolved value is tagged, that the tag matches the expected tag?
(selector (assoc selector-context :resolved-type field-type-name)))