/
core.cljc
1358 lines (1148 loc) · 44.8 KB
/
core.cljc
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
(ns com.wsscode.pathom.core
(:refer-clojure :exclude [ident?])
#?(:cljs
(:require-macros [com.wsscode.pathom.core]))
(:require
[clojure.spec.alpha :as s]
[clojure.core.async :as async :refer [go <! >!]]
[#?(:clj com.wsscode.async.async-clj
:cljs com.wsscode.async.async-cljs)
:as casync
:refer [go-catch <? let-chan chan? <?maybe <!maybe go-promise]]
[com.fulcrologic.guardrails.core :refer [>def >defn >fdef => | <-]]
[com.wsscode.pathom.parser :as pp]
[com.wsscode.pathom.misc :as p.misc]
[clojure.set :as set]
[clojure.walk :as walk]
[edn-query-language.core :as eql]
#?(:cljs [goog.object :as gobj])
[com.wsscode.pathom.trace :as pt])
#?(:clj
(:import (clojure.lang IAtom IDeref))))
;; pathom core
(declare atom?)
(>def ::env map?)
(>def ::attribute ::eql/property)
(>def ::reader-map (s/map-of keyword? ::reader))
(>def ::reader-seq (s/coll-of ::reader :kind vector? :into []))
(>def ::reader-fn fn?)
(>def ::optional? boolean?)
(>def ::reader
(s/or :fn ::reader-fn
:map ::reader-map
:list ::reader-seq))
(>def ::process-reader fn?)
(>def ::process-error fn?)
(>def ::error
(s/spec any?
:gen #(s/gen #{(ex-info "Generated sample error" {:some "data"})})))
(>def ::errors (s/map-of vector? any?))
(>def ::errors* #(atom? %))
(>def ::entity any?)
(>def ::entity-key keyword?)
(>def ::fail-fast? boolean?)
(>def ::map-key-transform
(s/fspec :args (s/cat :key any?)
:ret string?))
(>def ::map-value-transform
(s/fspec :args (s/cat :key any? :value any?)
:ret any?))
(>def ::placeholder-prefixes set?)
(>def ::js-key-transform ::map-key-transform)
(>def ::js-value-transform ::map-value-transform)
(>def ::parser fn?
#_(s/fspec :args (s/cat :env map? :tx ::eql/query)
:ret map?))
(>def ::wrap-read
(s/fspec :args (s/cat :reader ::reader-fn)
:ret ::reader-fn))
(>def ::wrap-parser
(s/fspec :args (s/cat :parser ::parser)
:ret ::parser))
(>def ::plugin (s/keys :opt [::wrap-read ::wrap-parser]))
#_(>def ::plugins
(s/with-gen (s/coll-of ::plugin :kind vector?) #(s/gen #{[]})))
(>def ::parent-join-key (s/or :prop ::eql/property
:ident ::eql/ident
:call ::eql/mutation-key))
(>def ::parent-query ::eql/join-query)
(>def ::union-path
(s/or :keyword ::eql/property
:fn fn?))
(>def ::async-request-cache-ch-size pos-int?)
(>def ::async-parser? boolean?)
(>def ::processing-sequence
"When processing a sequence item, this list is available at environment, it's intended
to use for batch optimizations, giving to the item the visibility of the whole."
(s/or :coll (s/coll-of map?)
:map (s/map-of any? map?)))
(>def ::path (s/coll-of (s/or :attr ::attribute
:ident ::eql/ident
:index nat-int?) :kind vector?))
(>def ::shape-descriptor
"Describes the shape of a nested map using maps, this is a way to efficiently check
for the presence of a specific path on data."
(s/map-of any? ::shape-descriptor))
(def break-values #{::reader-error ::not-found})
;; SUPPORT FUNCTIONS
(defn ast-properties
"Takes an AST and return a single set with all properties that appear in a query.
Example:
(-> [:foo {:bar [:baz]}] eql/query->ast pc/all-out-attributes)
; => #{:foo :bar :baz}"
[{:keys [children]}]
(reduce
(fn [attrs {:keys [key children] :as node}]
(cond-> (conj attrs key)
children
(into (ast-properties node))))
#{}
children))
(defn deep-merge [& xs]
"Merges nested maps without overwriting existing keys."
(if (every? #(or (map? %) (nil? %)) xs)
(apply merge-with deep-merge xs)
(last xs)))
(defn query->ast
"Given a query expression convert it into an AST."
[query-expr]
(pp/query->ast query-expr))
(defn query->ast1
"Call query->ast and return the first children."
[query-expr]
(-> (query->ast query-expr) :children first))
(defn ast->query [query-ast]
"Given an AST convert it back into a query expression."
(pp/ast->expr query-ast true))
(defn filter-ast [f ast]
(->> ast
(walk/prewalk
(fn filter-ast-walk [x]
(if (and (map? x)
(contains? x :children))
(update x :children #(filterv f %))
x)))))
(defn params
"Get params from env, always returns a map."
[env]
(-> env :ast :params (or {})))
(defn update-attribute-param
"Add attribute param, eg:
```
(p/update-attribute-param :keyword assoc :foo \"bar\") => (:keyword {:foo \"bar\"})
(p/update-attribute-param '(:keyword {:param \"prev\"}) assoc :foo \"bar\") => (:keyword {:foo \"bar\" :param \"prev\"})
```
"
[x f & args]
(if (seq? x)
(let [[k p] x]
(list k (apply f p args)))
(list x (apply f {} args))))
(defn optional-attribute [x]
(assert (or (keyword? x) (list x)) "Optional value must be a keyword or a parameterized attribute")
(update-attribute-param x assoc ::optional? true))
; alias for optional-attribute
(def ? optional-attribute)
(defn union-children?
"Given an AST point, check if the children is a union query type."
[ast]
(= :union (some-> ast :children first :type)))
(defn maybe-merge-union-ast [ast]
(if (union-children? ast)
(let [merged-children (into [] (mapcat :children) (some-> ast :children first :children))]
(assoc ast
:children merged-children
:query (eql/ast->query {:type :root :children merged-children})))
ast))
(defn merge-shapes
([a] a)
([a b]
(cond
(and (map? a) (map? b))
(merge-with merge-shapes a b)
(map? a) a
(map? b) b
:else b)))
(>defn ast->shape-descriptor
"Convert AST to shape descriptor format"
[ast]
[:edn-query-language.ast/node => ::shape-descriptor]
(reduce
(fn [m {:keys [key type children] :as node}]
(if (= :union type)
(let [unions (into [] (map ast->shape-descriptor) children)]
(reduce merge-shapes m unions))
(assoc m key (ast->shape-descriptor node))))
{}
(:children ast)))
(>defn map->shape-descriptor
"Convert Map to shape descriptor format"
[m]
[map? => ::shape-descriptor]
(reduce-kv
(fn [m k v]
(assoc m k
(cond
(map? v)
(map->shape-descriptor v)
(sequential? v)
(transduce
(comp (filter map?)
(map map->shape-descriptor))
merge-shapes
{}
v)
:else
{})))
{}
m))
(defn read-from* [{:keys [ast] :as env} reader]
(cond
(map? reader) (let [k (:key ast)]
(if-let [[_ v] (find reader k)]
(read-from* env v)
::continue))
(vector? reader) (let [res (into [] (comp (map #(read-from* env %))
(drop-while #(= % ::continue))
(take 1))
reader)]
(if (seq res)
(first res)
::continue))
(ifn? reader) (reader env)
:else (throw (ex-info "Can't process reader" {:reader reader}))))
(defn read-from
"Runs the read process for the reading, the reader can be a function, a vector or a map:
function: will receive the environment as argument
map: will dispatch from the ast key to a reader on the map value
vector: will try to run each reader in sequence, when a reader returns ::p/continue it will try the next"
[env reader]
(let-chan [res (read-from* env reader)]
(if (= res ::continue) ::not-found res)))
(defn reader
"Like read-from, pulling reader from environment."
[env]
(read-from env (::reader env)))
(defn native-map? [x]
#?(:clj (or (= (type x) clojure.lang.PersistentArrayMap)
(= (type x) clojure.lang.PersistentHashMap))
:cljs (or (= (type x) cljs.core/PersistentArrayMap)
(= (type x) cljs.core/PersistentHashMap))))
(defn transduce-maps
"Walk the structure and transduce every map with xform."
[xform input]
(walk/prewalk
(fn elide-items-walk [x]
(if (native-map? x)
(with-meta (into {} xform x) (meta x))
x))
input))
(defn transduce-children
"Recursively transduce children on the AST, you can use this to apply filter/transformations
on a whole AST. Each iteration of the transducer will get a single AST node to process.
```
(->> [:a {:b [:c :d]} :e]
(p/query->ast)
(p/transduce-children (remove (comp #{:a :c} :key)))
(p/ast->query))
; => [{:b [:d]} :e]
```"
[xform {:keys [children] :as node}]
(cond-> node
(seq children)
(update :children
(fn [children]
(into [] (comp xform (map #(transduce-children xform %))) children)))))
(def special-outputs #{::reader-error ::not-found})
(defn elide-items
"Removes any item on set item-set from the input"
[item-set input]
(with-meta
(transduce-maps (remove (fn [[_ v]] (contains? item-set v))) input)
(meta input)))
(defn elide-not-found
"Convert all ::p/not-found values of maps to nil"
[input]
(elide-items #{::not-found} input))
(defn elide-special-outputs
"Convert all ::p/not-found values of maps to nil"
[input]
(elide-items special-outputs input))
(def focus-subquery pp/focus-subquery)
(defn atom? [x]
#?(:clj (instance? IDeref x)
:cljs (satisfies? IDeref x)))
(defn normalize-atom [x] (if (atom? x) x (atom x)))
(defn raw-entity
[{::keys [entity-key] :as env}]
(get env (or entity-key ::entity)))
(defn maybe-atom [x]
(if (atom? x) (deref x) x))
(defn entity-value-merge
"This is used for merging new parsed attributes from entity, works like regular merge but if the value from the right
direction is not found, then the previous value will be kept."
[x y]
(if (identical? y ::not-found)
x
y))
(defn entity
"Fetch the entity according to the ::entity-key. If the entity is an IAtom, it will be derefed.
If a second argument is sent, calls the parser against current element to guarantee that some fields are loaded. This
is useful when you need to ensure some values are loaded in order to fetch some more complex data. NOTE: When using
this call with an explicit vector of attributes the parser will not be invoked for attributes that already exist in
the current value of the current entity."
([env]
(let [e (raw-entity env)]
(maybe-atom e)))
([{:keys [parser] :as env} attributes]
(let [e (entity env)]
(let-chan [res (parser env (filterv (-> e keys set complement) attributes))]
(if (map? res)
(merge-with entity-value-merge e res)
e)))))
(defn entity-attr
"Helper function to fetch a single attribute from current entity."
([env attr]
(let-chan [e (entity env [attr])]
(get e attr)))
([env attr default]
(let-chan [e (entity env [attr])]
(let [x (get e attr)]
(if (#{nil ::not-found} x)
default
x)))))
(defn entity! [{::keys [path] :as env} attributes]
(let-chan [e (entity env attributes)]
(let [missing (set/difference (set attributes)
(set (keys (elide-not-found e))))]
(if (seq missing)
(throw (ex-info (str "Entity attributes " (pr-str missing) " could not be realized")
{::entity e
::path path
::missing-attributes missing})))
e)))
(defn entity-attr!
"Like entity-attr. Raises an exception if the property can't be retrieved."
[env attr]
(let-chan [e (entity! env [attr])]
(get e attr)))
(defn swap-entity!
"Helper to swap the current entity value."
[env fn & args]
(let [e (raw-entity env)]
(if (atom? e)
(apply swap! e fn args)
(apply fn e args))))
(defn update-child
"Given an AST, find the child with a given key and run update against it."
[ast key & args]
(if-let [idx (some->> (:children ast)
(map-indexed vector)
(filter (comp #{key} :key second))
ffirst)]
(apply update-in ast [:children idx] args)
ast))
(defn update-recursive-depth
"Given an AST, find the child with a given key and run update against it."
[ast key & args]
(if-let [idx (some->> (:children ast)
(map-indexed vector)
(filter (comp #(and (= key (:key %))
(pos-int? (:query %))) second))
ffirst)]
(apply update-in ast [:children idx :query] args)
ast))
(defn remove-query-wildcard [query]
(into (with-meta [] (meta query)) (remove #{'*}) query))
(defn default-union-path [{:keys [query] :as env}]
(let [e (entity env)]
(if-let [path (some->> (keys query)
(filter #(and (contains? e %)
(not (break-values (get e %)))))
first)]
path)))
(defn placeholder-key? [{::keys [placeholder-prefixes]} k]
(let [placeholder-prefixes (or placeholder-prefixes #{">"})]
(and (keyword? k)
(contains? placeholder-prefixes (namespace k)))))
(>defn path-without-placeholders
[{::keys [path] :as env}]
[(s/keys :req [::path]) => ::path]
(into [] (remove #(placeholder-key? env %)) path))
(defn find-closest-non-placeholder-parent-join-key
"Find the closest parent key that's not a placeholder key."
[{::keys [path] :as env}]
(->> (or path []) rseq (drop 1) (remove #(placeholder-key? env %)) first))
(defn join
"Runs a parser with current sub-query. When run with an `entity` argument, that entity is set as the new environment
value of `::entity`, and the subquery is parsed with that new environment. When run without an `entity` it
parses the current subquery in the context of whatever entity was already in `::entity` of the env."
([entity {:keys [ast query] ::keys [entity-key] :as env}]
(if (atom? entity)
(if-let [env' (::env @entity)]
(do
(swap! entity dissoc ::env)
(join (assoc env'
:ast ast
:query query
entity-key entity)))
(join (assoc env entity-key entity)))
(if (::env entity)
(join (assoc (get entity ::env)
:ast ast
:query query
entity-key (atom (dissoc entity ::env))))
(join (assoc env entity-key (atom entity))))))
([{:keys [parser ast query]
::keys [union-path parent-query processing-sequence]
:as env}]
(let [e (entity env)
placeholder? (placeholder-key? env (:dispatch-key ast))
union-path (if (union-children? ast)
(let [union-path (or union-path default-union-path)
path (cond
(fn? union-path) (union-path env)
(keyword? union-path) (get (entity! env [union-path]) union-path))]
path))
query (if (union-children? ast)
(or (get query union-path) ::blank-union)
query)
env' (-> env
(cond-> union-path (update ::path conj union-path))
(assoc ::parent-query query
::parent-join-key (:key ast))
(cond-> (not placeholder?)
(dissoc ::pp/waiting ::pp/key-watchers)))
env' (if processing-sequence
(if (and (::stop-sequence? (meta processing-sequence))
(not placeholder?))
(dissoc env' ::processing-sequence)
(update env' ::processing-sequence vary-meta assoc ::stop-sequence? true))
env')]
(cond
(= ::blank-union query)
{}
(nil? query) e
(nat-int? query)
(if (zero? query)
nil
(let [parent-query' (-> (query->ast parent-query)
(update-recursive-depth (:key ast) dec)
(ast->query))]
(parser (assoc env' ::parent-query parent-query') (remove-query-wildcard parent-query'))))
(some #{'*} query)
(let-chan [computed-e (parser env' (remove-query-wildcard query))]
(merge (entity env') computed-e))
:else
(parser env' query)))))
(defn join-seq-parallel [{:keys [query]
::keys [entity-path-cache parent-query]
:as env} coll]
(let [query' (if (nat-int? query) parent-query query)]
(if (and (seq coll) (or (vector? query) (pos-int? query)))
(go-promise
(pt/tracing env {::pt/event ::parallel-sequence-loop
::pt/style {:fill "#e0e3a4"
:opacity "0.8"}}
(let [ast (eql/query->ast query')
check-ast-opt? (every? #(not (:children %)) (:children ast))
join-item (fn join-item [env entity]
(or (and
check-ast-opt?
(reduce
(fn [ent {:keys [key params]}]
(if-let [[_ v] (find entity key)]
(assoc ent (get params :pathom/as key) v)
(reduced nil)))
{}
(:children ast)))
(join entity env)))
env (assoc env ::processing-sequence coll)
[head & tail] coll
first-res (<?maybe (join-item (update env ::path conj 0) head))
from-chan (async/chan 10)
out-chan (async/chan 10)]
(async/onto-chan from-chan (map vector tail (range)))
(async/pipeline-async 10
out-chan
(fn join-seq-pipeline [[ent i] res-ch]
(go
(let [{::keys [path] :as env'} (update env ::path conj (inc i))
ent (merge (get @entity-path-cache path {}) ent)
res (<!maybe (join-item env' ent))]
(>! res-ch res)
(async/close! res-ch))))
from-chan)
(<! (async/into [first-res] out-chan)))))
[])))
(defn join-seq
"Runs the current subquery against the items of the given collection."
[{::pp/keys [parallel?] :as env} coll]
(pt/trace env {::pt/event ::join-seq ::seq-count (count coll)})
(if parallel?
(join-seq-parallel env coll)
(letfn [(join-item [ent out]
(join ent (-> env
(assoc ::processing-sequence coll)
(update ::path conj (count out)))))]
(loop [out []
[ent & tail] coll]
(if ent
(let [res (join-item ent out)]
(if (chan? res)
(go-promise
(loop [out [(<? res)]
[ent & tail] tail]
(if ent
(recur
(conj out (<? (join-item ent out)))
tail)
out)))
(recur (conj out res) tail)))
out)))))
(>defn join-map
"Runs the current subquery against the items of the given collection."
[env m]
[(s/keys) map?
=> (s/or :map map? :map-chan casync/chan?)]
(pt/trace env {::pt/event ::join-map ::seq-count (count m)})
(letfn [(join-item [k ent]
(join ent (-> env
(assoc ::processing-sequence m)
(update ::path conj k))))]
(loop [out {}
[pair & tail] m]
(if pair
(let [[k ent] pair
res (join-item k ent)]
(if (chan? res)
(go-promise
(loop [out {k (<? res)}
[pair & tail] tail]
(if-let [[k ent] pair]
(recur
(assoc out k (<? (join-item k ent)))
tail)
out)))
(recur (assoc out k res) tail)))
out))))
(defn ident? [x]
(and (vector? x)
(keyword? (first x))
(= 2 (count x))))
(defn ident-key* [key]
(if (vector? key) (first key)))
(defn ident-key
"The first element of an ident."
[{:keys [ast]}]
(let [key (some-> ast :key)]
(if (vector? key) (first key))))
(defn ident-value* [key]
(if (vector? key) (second key)))
(defn ident-value
"The second element of an ident"
[{:keys [ast]}]
(let [key (some-> ast :key)]
(if (sequential? key) (second key))))
(defn elide-ast-nodes
"Remove items from a query (AST) that have a key listed in the elision-set"
[{:keys [key union-key] :as ast} elision-set]
(let [union-elision? (contains? elision-set union-key)]
(when-not (or union-elision? (contains? elision-set key))
(update ast :children (fn [c] (if c (vec (keep #(elide-ast-nodes % elision-set) c))))))))
(defn normalize-env [{:keys [ast] :as env}]
(cond-> (update env ::path (fnil conj []) (:key ast))
(nil? (::entity-key env)) (assoc ::entity-key ::entity)))
(defn merge-queries* [qa qb]
(reduce (fn [ast {:keys [key type params] :as item-b}]
(if-let [[idx item] (->> ast :children
(keep-indexed #(if (-> %2 :key (= key)) [%1 %2]))
first)]
(cond
(or (= :join (:type item) type)
(= :prop (:type item) type))
(if (= (:params item) params)
(update-in ast [:children idx] merge-queries* item-b)
(reduced nil))
(and (= :prop (:type item))
(= :join type))
(assoc-in ast [:children idx] item-b)
(= :call type)
(reduced nil)
:else ast)
(update ast :children conj item-b)))
qa
(:children qb)))
(defn merge-queries [qa qb]
(some-> (merge-queries* (query->ast qa) (query->ast qb))
(ast->query)))
(defn normalize-query-variables
"Converts ident values and param values to ::p/var."
[query]
(->> (query->ast query)
(transduce-children
(map (fn [x]
(cond-> x
(ident? (:key x))
(assoc :key [(first (:key x)) ::var])
(:params x)
(update :params #(into {} (map (fn [[k _]] [k ::var])) %))))))
(ast->query)))
(defn query-id
"Generates a consistent hash from the query. The query first goes to a process to remove any
variables from idents and params, then we get the Clojure hash of it. You can use this to save
information about a query that can be used to correlate with the query later."
[query]
(hash (normalize-query-variables query)))
;; DISPATCH HELPERS
(defn key-dispatch [{:keys [ast]}]
(:key ast))
(defn entity-dispatch
"Dispatch on the first element (type) of an incoming ident."
[{:keys [ast]}]
(if (vector? (:key ast))
(first (:key ast))))
;; NODE HELPERS
(defn env-placeholder-reader
"Produces a reader that will respond to any keyword whose namespace
is in the set `(::placeholder-prefixes env)`. The join node logical
level stays the same as the parent where the placeholder node is
requested."
[{::keys [placeholder-prefixes] :as env}]
(assert placeholder-prefixes "To use env-placeholder-reader please add ::p/placeholder-prefixes to your environment.")
(if (placeholder-key? env (-> env :ast :dispatch-key))
(join env)
::continue))
(defn lift-placeholders-ast
"This will lift the AST from placeholders to the same level of the query, as if there was not placeholders in it."
[env ast]
(walk/postwalk
(fn [x]
(if-let [children (:children x)]
(let [{placeholders true
regular false} (group-by #(and (= :join (:type %))
(placeholder-key? env (:dispatch-key %))) children)]
(as-> (assoc x :children (or regular [])) <>
(reduce merge-queries* <> placeholders)))
x))
ast))
(defn lift-placeholders
"This will lift the queries from placeholders to the same level of the query, as if there was not placeholders in it."
[env query]
(->> query
query->ast
(lift-placeholders-ast env)
ast->query))
;; BUILT-IN READERS
(defn join-children?
"Children should join when there is a query, unless the value is marked as final."
[{:keys [query]} v]
(and query (not (::final (meta v)))))
(defn map-reader
"Map reader will try to find the ast key on the current entity and output it. When the value is a map and a
sub query is present, it will apply the sub query on that value (recursively). When the value is a sequence,
map-reader will do a join on each of the items (and apply sub queries if it's present and values are maps.
Map-reader will defer the read when the key is not present at entity."
[{:keys [ast query] :as env}]
(let [key (:key ast)
entity (entity env)]
(if (contains? entity key)
(let [v (get entity key)]
(cond
(sequential? v)
(if (join-children? env v)
(join-seq env v)
v)
(and (map? v)
(or (::map-of-maps (meta v))
(::map-of-maps (meta query))))
(if (join-children? env v)
(join-map env v)
v)
:else
(if (and (map? v) (join-children? env v))
(join v env)
v)))
::continue)))
(defn map-reader*
"Like map-reader, but it has extra options (read from the environment):
map-key-transform: (fn [key]) will transform the key on the AST before trying to match with entity key
map-value-transform: (fn [key value]) will transform the output value after reading from the entity.
The reason to have a separated reader is so the plain version (map-reader) can be faster by avoiding checking
the presence of transform functions."
[{::keys [map-key-transform map-value-transform]}]
(fn [{:keys [ast query]
::keys [entity-key]
:as env}]
(let [key (cond-> (:key ast) map-key-transform map-key-transform)
entity (entity env)]
(if (contains? entity key)
(let [v (get entity key)]
(cond
(sequential? v)
(if (join-children? env v)
(join-seq env v)
v)
(and (map? v)
(or (::map-of-maps (meta v))
(::map-of-maps (meta query))))
(if (join-children? env v)
(join-map env v)
v)
:else
(if (and (map? v) (join-children? env v))
(join (assoc env entity-key v))
(cond->> v
map-value-transform
(map-value-transform (:key ast))))))
::continue))))
#?(:cljs
(defn js-obj-reader
"Like map-reader*, but handles plain Javascript objects instead of Clojure maps."
[{:keys [query ast]
::keys [js-key-transform js-value-transform entity-key]
:as env
:or {js-key-transform name
js-value-transform (fn [_ v] v)}}]
(let [js-key (js-key-transform (:key ast))
entity (entity env)]
(if (gobj/containsKey entity js-key)
(let [v (gobj/get entity js-key)]
(if (js/Array.isArray v)
(if query
(join-seq env (array-seq v))
v)
(if (and query (= (type v) js/Object))
(join (assoc env entity-key v))
(js-value-transform (:key ast) v))))
::continue))))
(defn ident-join-reader
"This reader will join on any ident join, the entity for the join will be a map containing the same
key and value expressed on the ident, eg: [{[:id 123] [:id]}], the join entry will be {:id 123}."
[env]
(if-let [key (ident-key env)]
(join {key (ident-value env)} env)
::continue))
;; PLUGINS
; Helpers
(defn pre-process-parser-plugin
"Helper to create a plugin that can view/modify the env/tx of a top-level request.
f - (fn [{:keys [env tx]}] {:env new-env :tx new-tx})
If the function returns no env or tx, then the parser will not be called (aborts the parse)"
[f]
{::wrap-parser
(fn transform-parser-out-plugin-external [parser]
(fn transform-parser-out-plugin-internal [env tx]
(let [{:keys [env tx]} (f {:env env :tx tx})]
(if (and (map? env) (seq tx))
(parser env tx)
{}))))})
(defn post-process-parser-plugin
"Helper to create a plugin to work on the parser output. `f` will run once with the parser final result."
[f]
{::wrap-parser
(fn transform-parser-out-plugin-external [parser]
(fn transform-parser-out-plugin-internal [env tx]
(let-chan [res (parser env tx)]
(f res))))})
(def elide-special-outputs-plugin
(post-process-parser-plugin elide-special-outputs))
; Exception
(defn error-message [err]
#?(:clj (.getMessage err)
:cljs (.-message err)))
(defn error-str [err]
#?(:clj
(let [msg (.getMessage err)
data (ex-data err)]
(cond-> (str (type err))
msg (str ": " msg)
data (str " - " (pr-str data))))
:cljs
(let [msg (.-message err)
data (ex-data err)]
(cond-> msg
data (str " - " (pr-str data))))))
(defn update-action
"Helper function to update a mutation action."
[m f]
(if (contains? m :action)
(update m :action f)
m))
(defn process-error [{::keys [process-error] :as env} e]
(if process-error (process-error env e)
(error-str e)))
(defn add-error [{::keys [errors* path] :as env} e]
(when errors*
(swap! errors* assoc path (process-error env e)))
::reader-error)
(defn wrap-handle-exception [reader]
(fn wrap-handle-exception-internal
[{::keys [fail-fast?] :as env}]
(if fail-fast?
(reader env)
(try
(let [x (reader env)]
(if (chan? x)
(go
(try
(<? x)
(catch #?(:clj Throwable :cljs :default) e
(add-error env e))))
x))
(catch #?(:clj Throwable :cljs :default) e
(add-error env e))))))
(defn wrap-mutate-handle-exception [mutate]
(fn wrap-mutate-handle-exception-internal
[{::keys [process-error fail-fast?] :as env} k p]
(if fail-fast?
(mutate env k p)
(try
(update-action (mutate env k p)
(fn [action]
(fn []
(try
(let [res (action)]
(if (chan? res)
(go
(try
(<? res)
(catch #?(:clj Throwable :cljs :default) e
(if process-error (process-error env e)
{::reader-error (error-str e)}))))
res))
(catch #?(:clj Throwable :cljs :default) e
(if process-error (process-error env e)
{::reader-error (error-str e)}))))))
(catch #?(:clj Throwable :cljs :default) e
{:action
(fn []
(if process-error (process-error env e)
{::reader-error (error-str e)}))})))))
(defn wrap-parser-exception [parser]
(fn wrap-parser-exception-internal [env tx]
(let [errors (atom {})]
(let-chan [res (parser (assoc env ::errors* errors) tx)]
(cond-> res
(seq @errors) (assoc ::errors @errors))))))
(def error-handler-plugin
{::wrap-read wrap-handle-exception
::wrap-parser wrap-parser-exception
::wrap-mutate wrap-mutate-handle-exception})
(def trace-plugin pt/trace-plugin)
(defn collapse-error-path [m path]
"Reduces the error path to the last available nesting on the map m."
(vec
(loop [path' path]
(if (zero? (count path'))
(take 1 path)
(if (get-in m path')
path'
(recur (butlast path')))))))
(defn raise-errors [data]
"Extract errors from the data root and inject those in the same level where
the error item is present. For example:
{:query {:item :com.wsscode.pathom/reader-error}
:com.wsscode.pathom.core/errors
{[:query :item] {:error \"some error\"}}}
Is turned into:
{:query {:item :com.wsscode.pathom/reader-error
:com.wsscode.pathom.core/errors {:item {:error \"some error\"}}}
This makes easier to reach for the error when rendering the UI."