Source file graphql_schema.ml
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
module List = struct
include List
let assoc_exn = assoc
let assoc x ys = try Some (assoc_exn x ys) with Not_found -> None
let find_exn = find
let find cond xs = try Some (find_exn cond xs) with Not_found -> None
module Result = struct
let rec join ?(memo=[]) = function
| [] -> Ok (List.rev memo)
| (Error _ as err)::_ -> err
| (Ok x)::xs -> join ~memo:(x::memo) xs
let all f xs =
List.map f xs |> join
end
end
module Option = struct
let map x ~f = match x with None -> None | Some y -> Some (f y)
end
module type IO = sig
type +'a t
val return : 'a -> 'a t
val bind : 'a t -> ('a -> 'b t) -> 'b t
module Stream : sig
type +'a io
type 'a t
val map : 'a t -> ('a -> 'b io) -> 'b t
val iter : 'a t -> ('a -> unit io) -> unit io
val close : 'a t -> unit
end with type 'a io := 'a t
end
module Make (Io : IO) = struct
module Io = struct
include Io
let map x ~f = bind x (fun x' -> return (f x'))
let ok x = Io.return (Ok x)
let error x = Io.return (Error x)
let rec all = function
| [] -> Io.return []
| x::xs ->
bind (all xs) (fun xs' ->
map x ~f:(fun x' -> x'::xs')
)
module Result = struct
let bind x f = bind x (function Ok x' -> f x' | Error _ as err -> Io.return err)
let map_error x ~f = map x ~f:(function Ok _ as ok -> ok | Error err -> Error (f err))
let map x ~f = map x ~f:(function Ok x' -> Ok (f x') | Error _ as err -> err)
end
let rec map_s ?(memo=[]) f = function
| [] -> Io.return (List.rev memo)
| x::xs ->
bind (f x) (fun x' -> map_s ~memo:(x'::memo) f xs)
let map_p f xs = List.map f xs |> all
module Infix = struct
let (>>|) x f = map x ~f
let (>>=?) = Result.bind
end
end
module StringMap = struct
include Map.Make(String)
exception Missing_key of string
let find_exn key t = try find key t with Not_found -> raise (Missing_key key)
let find k t = try Some (find_exn k t) with Missing_key _ -> None
end
module StringSet = Set.Make(String)
type variable_map = Graphql_parser.const_value StringMap.t
type deprecated =
| NotDeprecated
| Deprecated of string option
type 'a enum_value = {
name : string;
doc : string option;
deprecated : deprecated;
value : 'a;
}
let enum_value ?doc ?(deprecated=NotDeprecated) name ~value =
{ name; doc; deprecated; value; }
let id : 'a. 'a -> 'a = fun x -> x
module Arg = struct
open Rresult
type _ arg_typ =
| Scalar : {
name : string;
doc : string option;
coerce : Graphql_parser.const_value -> ('a, string) result;
} -> 'a option arg_typ
| Object : {
name : string;
doc : string option;
fields : ('a, 'b) arg_list;
coerce : 'b;
} -> 'a option arg_typ
| Enum : {
name : string;
doc : string option;
values : 'a enum_value list;
} -> 'a option arg_typ
| List : 'a arg_typ -> 'a list option arg_typ
| NonNullable : 'a option arg_typ -> 'a arg_typ
and _ arg =
| Arg : {
name : string;
doc : string option;
typ : 'a arg_typ;
} -> 'a arg
| DefaultArg : {
name : string;
doc : string option;
typ : 'a option arg_typ;
default : 'a;
} -> 'a arg
and (_, _) arg_list =
| [] : ('a, 'a) arg_list
| (::) : 'a arg * ('b, 'c) arg_list -> ('b, 'a -> 'c) arg_list
let arg ?doc name ~typ =
Arg { name; doc; typ }
let arg' ?doc name ~typ ~default =
DefaultArg { name; doc; typ; default }
let scalar ?doc name ~coerce =
Scalar { name; doc; coerce }
let enum ?doc name ~values =
Enum { name; doc; values }
let obj ?doc name ~fields ~coerce =
Object { name; doc; fields; coerce }
let rec string_of_const_value : Graphql_parser.const_value -> string = function
| `Null -> "null"
| `Int i -> string_of_int i
| `Float f -> string_of_float f
| `String s -> Printf.sprintf "\"%s\"" s
| `Bool b -> string_of_bool b
| `Enum e -> e
| `List l ->
let values = List.map (fun i -> string_of_const_value i) l in
Printf.sprintf "[%s]" (String.concat ", " values)
| `Assoc a ->
let values =
List.map
(fun (k, v) ->
Printf.sprintf "%s: %s" k (string_of_const_value v) )
a
in
Printf.sprintf "{%s}" (String.concat ", " values)
let rec string_of_arg_typ : type a. a arg_typ -> string = function
| Scalar a -> a.name
| Object a -> a.name
| Enum a -> a.name
| List a -> Printf.sprintf "[%s]" (string_of_arg_typ a)
| NonNullable a -> Printf.sprintf "%s!" (string_of_arg_typ a)
let eval_arg_error ?(field_type="field") ~field_name ~arg_name arg_typ value =
let found_str =
match value with
| Some v -> Printf.sprintf "found %s" (string_of_const_value v)
| None -> "but not provided"
in
Printf.sprintf "Argument `%s` of type `%s` expected on %s `%s`, %s."
arg_name
(string_of_arg_typ arg_typ)
field_type
field_name
found_str
let int = Scalar {
name = "Int";
doc = None;
coerce = function
| `Int n -> Ok n
| _ -> Error "Invalid int"
}
let string = Scalar {
name = "String";
doc = None;
coerce = function
| `String s -> Ok s
| _ -> Error "Invalid string"
}
let float = Scalar {
name = "Float";
doc = None;
coerce = function
| `Float f -> Ok f
| `Int n -> Ok (float_of_int n)
| _ -> Error "Invalid float"
}
let bool = Scalar {
name = "Boolean";
doc = None;
coerce = function
| `Bool b -> Ok b
| _ -> Error "Invalid boolean"
}
let guid = Scalar {
name = "ID";
doc = None;
coerce = function
| `String s -> Ok s
| `Int n -> Ok (string_of_int n)
| _ -> Error "Invalid ID"
}
let non_null typ = NonNullable typ
let list typ = List typ
let rec value_to_const_value variable_map = function
| `Null -> `Null
| `Int _ as i -> i
| `Float _ as f -> f
| `String _ as s -> s
| `Bool _ as b -> b
| `Enum _ as e -> e
| `Variable v -> StringMap.find_exn v variable_map
| `List xs -> `List (List.map (value_to_const_value variable_map) xs)
| `Assoc props ->
let props' = List.map (fun (name, value) -> name, value_to_const_value variable_map value) props in
`Assoc props'
let rec eval_arglist
: type a b. variable_map
-> ?field_type:string
-> field_name:string
-> (a, b) arg_list
-> (string * Graphql_parser.value) list
-> b
-> (a, string) result =
fun variable_map ?field_type ~field_name arglist key_values f ->
match arglist with
| [] -> Ok f
| (DefaultArg arg)::arglist' ->
let arglist'' = (Arg { name = arg.name; doc = arg.doc; typ = arg.typ })::arglist' in
eval_arglist variable_map ?field_type ~field_name arglist'' key_values (function
| None -> f arg.default
| Some value -> f value
)
| (Arg arg)::arglist' ->
try
let value = List.assoc arg.name key_values in
let const_value = Option.map value ~f:(value_to_const_value variable_map) in
eval_arg variable_map ?field_type ~field_name ~arg_name:arg.name arg.typ const_value >>= fun coerced ->
eval_arglist variable_map ?field_type ~field_name arglist' key_values (f coerced)
with StringMap.Missing_key key -> Error (Format.sprintf "Missing variable `%s`" key)
and eval_arg
: type a. variable_map
-> ?field_type:string
-> field_name:string
-> arg_name:string
-> a arg_typ
-> Graphql_parser.const_value option
-> (a, string) result =
fun variable_map ?field_type ~field_name ~arg_name typ value ->
match (typ, value) with
| NonNullable _, None -> Error (eval_arg_error ?field_type ~field_name ~arg_name typ value)
| NonNullable _, Some `Null -> Error (eval_arg_error ?field_type ~field_name ~arg_name typ value)
| Scalar _, None -> Ok None
| Scalar _, Some `Null -> Ok None
| Object _, None -> Ok None
| Object _, Some `Null -> Ok None
| List _, None -> Ok None
| List _, Some `Null -> Ok None
| Enum _, None -> Ok None
| Enum _, Some `Null -> Ok None
| Scalar s, Some value ->
begin match (s.coerce value) with
| Ok coerced -> Ok (Some coerced)
| Error _ -> Error (eval_arg_error ?field_type ~field_name ~arg_name typ (Some value))
end
| Object o, Some value ->
begin match value with
| `Assoc props ->
let props' = (props :> (string * Graphql_parser.value) list) in
eval_arglist variable_map ?field_type ~field_name o.fields props' o.coerce >>| fun coerced ->
Some coerced
| _ -> Error (eval_arg_error ?field_type ~field_name ~arg_name typ (Some value))
end
| List typ, Some value ->
begin match value with
| `List values ->
let option_values = List.map (fun x -> Some x) values in
List.Result.all (eval_arg variable_map ?field_type ~field_name ~arg_name typ) option_values >>| fun coerced ->
Some coerced
| value -> eval_arg variable_map ?field_type ~field_name ~arg_name typ (Some value) >>| fun coerced ->
(Some [coerced] : a)
end
| NonNullable typ, value ->
eval_arg variable_map ?field_type ~field_name ~arg_name typ value >>= (function
| Some value -> Ok value
| None -> Error (eval_arg_error ?field_type ~field_name ~arg_name typ None))
| Enum e, Some value ->
begin match value with
| `Enum v
| `String v ->
begin match List.find (fun enum_value -> enum_value.name = v) e.values with
| Some enum_value -> Ok (Some enum_value.value)
| None -> Error (Printf.sprintf "Invalid enum value for argument `%s` on field `%s`" arg_name field_name)
end
| _ -> Error (Printf.sprintf "Expected enum for argument `%s` on field `%s`" arg_name field_name)
end
end
type 'a scalar = {
name : string;
doc : string option;
coerce : 'a -> Yojson.Basic.json;
}
type 'a enum = {
name : string;
doc : string option;
values : 'a enum_value list;
}
type fragment_map = Graphql_parser.fragment StringMap.t
type 'ctx resolve_info = {
ctx : 'ctx;
field : Graphql_parser.field;
fragments : fragment_map;
variables : variable_map;
}
type ('ctx, 'src) obj = {
name : string;
doc : string option;
fields : ('ctx, 'src) field list Lazy.t;
abstracts : abstract list ref;
}
and (_, _) field =
Field : {
name : string;
doc : string option;
deprecated : deprecated;
typ : ('ctx, 'out) typ;
args : ('a, 'args) Arg.arg_list;
resolve : 'ctx resolve_info -> 'src -> 'args;
lift : 'a -> ('out, string) result Io.t;
} -> ('ctx, 'src) field
and (_, _) typ =
| Object : ('ctx, 'src) obj -> ('ctx, 'src option) typ
| List : ('ctx, 'src) typ -> ('ctx, 'src list option) typ
| NonNullable : ('ctx, 'src option) typ -> ('ctx, 'src) typ
| Scalar : 'src scalar -> ('ctx, 'src option) typ
| Enum : 'src enum -> ('ctx, 'src option) typ
| Abstract : abstract -> ('ctx, ('ctx, 'a) abstract_value option) typ
and any_typ =
| AnyTyp : (_, _) typ -> any_typ
| AnyArgTyp : _ Arg.arg_typ -> any_typ
and abstract = {
name : string;
doc : string option;
kind : [`Union | `Interface of abstract_field list Lazy.t];
mutable types : any_typ list;
}
and abstract_field =
AbstractField : (_, _) field -> abstract_field
and ('ctx, 'a) abstract_value =
AbstractValue : ('ctx, 'src option) typ * 'src -> ('ctx, 'a) abstract_value
type 'ctx subscription_field =
SubscriptionField : {
name : string;
doc : string option;
deprecated : deprecated;
typ : ('ctx, 'out) typ;
args : (('out Io.Stream.t, string) result Io.t, 'args) Arg.arg_list;
resolve : 'ctx resolve_info -> 'args;
} -> 'ctx subscription_field
type 'ctx subscription_obj = {
name : string;
doc : string option;
fields : 'ctx subscription_field list;
}
type ('ctx, 'a) abstract_typ = ('ctx, ('ctx, 'a) abstract_value option) typ
type directive_location = [
| `Query
| `Mutation
| `Subscription
| `Field
| `Fragment_definition
| `Fragment_spread
| `Inline_fragment
| `Variable_definition
]
type directive =
Directive : {
name : string;
doc : string option;
locations : directive_location list;
args : ([ `Skip | `Include ], 'args) Arg.arg_list;
resolve : 'args;
} -> directive
type 'ctx schema = {
query : ('ctx, unit) obj;
mutation : ('ctx, unit) obj option;
subscription : 'ctx subscription_obj option;
}
let schema ?(mutation_name="mutation")
?mutations
?(subscription_name="subscription")
?subscriptions
?(query_name="query")
fields = {
query = {
name = query_name;
doc = None;
abstracts = ref [];
fields = lazy fields;
};
mutation = Option.map mutations ~f:(fun fields ->
{
name = mutation_name;
doc = None;
abstracts = ref [];
fields = lazy fields;
}
);
subscription = Option.map subscriptions ~f:(fun fields ->
{
name = subscription_name;
doc = None;
fields;
}
)
}
let obj ?doc name ~fields =
let rec o = Object { name; doc; fields = lazy (fields o); abstracts = ref []} in
o
let field ?doc ?(deprecated=NotDeprecated) name ~typ ~args ~resolve =
Field { name; doc; deprecated; typ; args; resolve; lift = Io.ok }
let io_field ?doc ?(deprecated=NotDeprecated) name ~typ ~args ~resolve =
Field { name; doc; deprecated; typ; args; resolve; lift = id }
let abstract_field ?doc ?(deprecated=NotDeprecated) name ~typ ~args =
AbstractField (Field { lift = Io.ok; name; doc; deprecated; typ; args; resolve = Obj.magic () })
let subscription_field ?doc ?(deprecated=NotDeprecated) name ~typ ~args ~resolve =
SubscriptionField { name; doc; deprecated; typ; args; resolve }
let enum ?doc name ~values =
Enum { name; doc; values }
let scalar ?doc name ~coerce =
Scalar { name; doc; coerce }
let list typ =
List typ
let non_null typ =
NonNullable typ
let union ?doc name =
Abstract { name; doc; types = []; kind = `Union }
let interface ?doc name ~fields =
let rec i = Abstract { name; doc; types = []; kind = `Interface (lazy (fields i)) } in
i
let add_type abstract_typ typ =
match (abstract_typ, typ) with
| Abstract a, Object o ->
a.types <- (AnyTyp typ)::a.types;
o.abstracts := a :: !(o.abstracts);
fun src -> AbstractValue (typ, src)
| _ ->
invalid_arg "Arguments must be Interface/Union and Object"
let obj_of_subscription_obj {name; doc; fields} =
let fields = List.map
(fun (SubscriptionField {name; doc; deprecated; typ; args; resolve}) ->
Field { lift = Obj.magic (); name; doc; deprecated; typ; args; resolve = (fun ctx () -> resolve ctx) })
fields
in
{ name; doc; abstracts = ref []; fields = lazy fields }
let int : 'ctx. ('ctx, int option) typ = Scalar {
name = "Int";
doc = None;
coerce = fun i -> `Int i;
}
let string : 'ctx. ('ctx, string option) typ = Scalar {
name = "String";
doc = None;
coerce = fun s ->`String s;
}
let bool : 'ctx. ('ctx, bool option) typ = Scalar {
name = "Boolean";
doc = None;
coerce = fun b -> `Bool b;
}
let float : 'ctx. ('ctx, float option) typ = Scalar {
name = "Float";
doc = None;
coerce = fun f -> `Float f;
}
let guid : 'ctx. ('ctx, string option) typ = Scalar {
name = "ID";
doc = None;
coerce = fun x -> `String x;
}
let skip_directive = Directive {
name = "skip";
doc = Some "Directs the executor to skip this field or fragment when the `if` argument is true.";
locations = [`Field; `Fragment_spread; `Inline_fragment];
args = Arg.[
arg "if" ~doc:"Skipped when true." ~typ:(non_null bool)
];
resolve = function
| true -> `Skip
| false -> `Include
}
let include_directive = Directive {
name = "include";
doc = Some "Directs the executor to include this field or fragment only when the `if` argument is true.";
locations = [`Field; `Fragment_spread; `Inline_fragment];
args = Arg.[
arg "if" ~doc:"Included when true." ~typ:(non_null bool)
];
resolve = function
| true -> `Include
| false -> `Skip
}
module Introspection = struct
type any_field =
| AnyField : (_, _) field -> any_field
| AnyArgField : _ Arg.arg -> any_field
type any_arg = AnyArg : _ Arg.arg -> any_arg
type any_enum_value = AnyEnumValue : _ enum_value -> any_enum_value
let unless_visited (result, visited) name f =
if StringSet.mem name visited then
result, visited
else
f (result, visited)
let rec types : type ctx src. ?memo:(any_typ list * StringSet.t) -> (ctx, src) typ -> (any_typ list * StringSet.t) = fun ?(memo=([], StringSet.empty)) typ ->
match typ with
| List typ -> types ~memo typ
| NonNullable typ -> types ~memo typ
| Scalar s as scalar ->
unless_visited memo s.name (fun (result, visited) ->
(AnyTyp scalar)::result, StringSet.add s.name visited
)
| Enum e as enum ->
unless_visited memo e.name (fun (result, visited) ->
(AnyTyp enum)::result, StringSet.add e.name visited
)
| Object o as obj ->
unless_visited memo o.name (fun (result, visited) ->
let result' = (AnyTyp obj)::result in
let visited' = StringSet.add o.name visited in
let reducer = fun memo (Field f) ->
let memo' = types ~memo f.typ in
arg_list_types memo' f.args
in
List.fold_left reducer (result', visited') (Lazy.force o.fields)
)
| Abstract a as abstract ->
unless_visited memo a.name (fun (result, visited) ->
let result' = (AnyTyp abstract)::result in
let visited' = StringSet.add a.name visited in
List.fold_left (fun memo typ -> match typ with
| AnyTyp typ -> types ~memo typ
| AnyArgTyp _ -> failwith "Abstracts can't have argument types")
(result', visited') a.types
)
and arg_types : type a. (any_typ list * StringSet.t) -> a Arg.arg_typ -> (any_typ list * StringSet.t) = fun memo argtyp ->
match argtyp with
| Arg.List typ -> arg_types memo typ
| Arg.NonNullable typ -> arg_types memo typ
| Arg.Scalar s as scalar ->
unless_visited memo s.name (fun (result, visited) ->
(AnyArgTyp scalar)::result, StringSet.add s.name visited
)
| Arg.Enum e as enum ->
unless_visited memo e.name (fun (result, visited) ->
(AnyArgTyp enum)::result, StringSet.add e.name visited
)
| Arg.Object o as obj ->
unless_visited memo o.name (fun (result, visited) ->
let memo' = (AnyArgTyp obj)::result, StringSet.add o.name visited in
arg_list_types memo' o.fields
)
and arg_list_types : type a b. (any_typ list * StringSet.t) -> (a, b) Arg.arg_list -> (any_typ list * StringSet.t) = fun memo arglist ->
let open Arg in
match arglist with
| [] -> memo
| arg::args ->
let memo' = match arg with
| Arg a -> arg_types memo a.typ
| DefaultArg a -> arg_types memo a.typ
in arg_list_types memo' args
let rec args_to_list : type a b. ?memo:any_arg list -> (a, b) Arg.arg_list -> any_arg list = fun ?memo:(memo=[]) arglist ->
let open Arg in
match arglist with
| [] ->
memo
| arg::args ->
let memo' = List.cons (AnyArg arg) memo in
args_to_list ~memo:memo' args
let no_abstracts = ref []
let __type_kind = Enum {
name = "__TypeKind";
doc = None;
values = [
{
name="SCALAR";
doc=None;
deprecated=NotDeprecated;
value=`Scalar;
};
{
name="OBJECT";
doc=None;
deprecated=NotDeprecated;
value=`Object;
};
{
name="INTERFACE";
doc=None;
deprecated=NotDeprecated;
value=`Interface;
};
{
name="UNION";
doc=None;
deprecated=NotDeprecated;
value=`Union;
};
{
name="ENUM";
doc=None;
deprecated=NotDeprecated;
value=`Enum;
};
{
name="INPUT_OBJECT";
doc=None;
deprecated=NotDeprecated;
value=`InputObject;
};
{
name="LIST";
doc=None;
deprecated=NotDeprecated;
value=`List;
};
{
name="NON_NULL";
doc=None;
deprecated=NotDeprecated;
value=`NonNull;
};
]
}
let __enum_value : 'ctx. ('ctx, any_enum_value option) typ = Object {
name = "__EnumValue";
doc = None;
abstracts = no_abstracts;
fields = lazy [
Field {
name = "name";
doc = None;
deprecated = NotDeprecated;
typ = NonNullable string;
args = Arg.[];
lift = Io.ok;
resolve = fun _ (AnyEnumValue enum_value) -> enum_value.name;
};
Field {
name = "description";
doc = None;
deprecated = NotDeprecated;
typ = string;
args = Arg.[];
lift = Io.ok;
resolve = fun _ (AnyEnumValue enum_value) -> enum_value.doc;
};
Field {
name = "isDeprecated";
doc = None;
deprecated = NotDeprecated;
typ = NonNullable bool;
args = Arg.[];
lift = Io.ok;
resolve = fun _ (AnyEnumValue enum_value) -> enum_value.deprecated <> NotDeprecated;
};
Field {
name = "deprecationReason";
doc = None;
deprecated = NotDeprecated;
typ = string;
args = Arg.[];
lift = Io.ok;
resolve = fun _ (AnyEnumValue enum_value) ->
match enum_value.deprecated with
| Deprecated reason -> reason
| NotDeprecated -> None
}
]
}
let rec __input_value : 'ctx. ('ctx, any_arg option) typ = Object {
name = "__InputValue";
doc = None;
abstracts = no_abstracts;
fields = lazy [
Field {
name = "name";
doc = None;
deprecated = NotDeprecated;
typ = NonNullable string;
args = Arg.[];
lift = Io.ok;
resolve = fun _ (AnyArg arg) -> match arg with
| Arg.DefaultArg a -> a.name
| Arg.Arg a -> a.name
};
Field {
name = "description";
doc = None;
deprecated = NotDeprecated;
typ = string;
args = Arg.[];
lift = Io.ok;
resolve = fun _ (AnyArg arg) -> match arg with
| Arg.DefaultArg a -> a.doc
| Arg.Arg a -> a.doc
};
Field {
name = "type";
doc = None;
deprecated = NotDeprecated;
typ = NonNullable __type;
args = Arg.[];
lift = Io.ok;
resolve = fun _ (AnyArg arg) -> match arg with
| Arg.DefaultArg a -> AnyArgTyp a.typ
| Arg.Arg a -> AnyArgTyp a.typ
};
Field {
name = "defaultValue";
doc = None;
deprecated = NotDeprecated;
typ = string;
args = Arg.[];
lift = Io.ok;
resolve = fun _ (AnyArg _) -> None
}
]
}
and __type : 'ctx . ('ctx, any_typ option) typ = Object {
name = "__Type";
doc = None;
abstracts = no_abstracts;
fields = lazy [
Field {
name = "kind";
doc = None;
deprecated = NotDeprecated;
typ = NonNullable __type_kind;
args = Arg.[];
lift = Io.ok;
resolve = fun _ t -> match t with
| AnyTyp (Object _) -> `Object
| AnyTyp (Abstract { kind = `Union; _ }) -> `Union
| AnyTyp (Abstract { kind = `Interface _; _ }) -> `Interface
| AnyTyp (List _) -> `List
| AnyTyp (Scalar _) -> `Scalar
| AnyTyp (Enum _) -> `Enum
| AnyTyp (NonNullable _) -> `NonNull
| AnyArgTyp (Arg.Object _) -> `InputObject
| AnyArgTyp (Arg.List _) -> `List
| AnyArgTyp (Arg.Scalar _) -> `Scalar
| AnyArgTyp (Arg.Enum _) -> `Enum
| AnyArgTyp (Arg.NonNullable _) -> `NonNull
};
Field {
name = "name";
doc = None;
deprecated = NotDeprecated;
typ = string;
args = Arg.[];
lift = Io.ok;
resolve = fun _ t -> match t with
| AnyTyp (Object o) -> Some o.name
| AnyTyp (Scalar s) -> Some s.name
| AnyTyp (Enum e) -> Some e.name
| AnyTyp (Abstract a) -> Some a.name
| AnyArgTyp (Arg.Object o) -> Some o.name
| AnyArgTyp (Arg.Scalar s) -> Some s.name
| AnyArgTyp (Arg.Enum e) -> Some e.name
| _ -> None;
};
Field {
name = "description";
doc = None;
deprecated = NotDeprecated;
typ = string;
args = Arg.[];
lift = Io.ok;
resolve = fun _ t -> match t with
| AnyTyp (Object o) -> o.doc
| AnyTyp (Scalar s) -> s.doc
| AnyTyp (Enum e) -> e.doc
| AnyTyp (Abstract a) -> a.doc
| AnyArgTyp (Arg.Object o) -> o.doc
| AnyArgTyp (Arg.Scalar s) -> s.doc
| AnyArgTyp (Arg.Enum e) -> e.doc
| _ -> None
};
Field {
name = "fields";
doc = None;
deprecated = NotDeprecated;
typ = List (NonNullable __field);
args = Arg.[];
lift = Io.ok;
resolve = fun _ t -> match t with
| AnyTyp (Object o) ->
Some (List.map (fun f -> AnyField f) (Lazy.force o.fields))
| AnyTyp (Abstract { kind = `Interface fields; _ }) ->
Some (List.map (fun (AbstractField f) -> AnyField f) (Lazy.force fields))
| AnyArgTyp (Arg.Object o) ->
let arg_list = args_to_list o.fields in
Some (List.map (fun (AnyArg f) -> AnyArgField f) arg_list)
| _ -> None
};
Field {
name = "interfaces";
doc = None;
deprecated = NotDeprecated;
typ = List (NonNullable __type);
args = Arg.[];
lift = Io.ok;
resolve = fun _ t -> match t with
| AnyTyp (Object o) ->
let interfaces = List.filter (function | { kind = `Interface _; _} -> true | _ -> false) !(o.abstracts) in
Some (List.map (fun i -> AnyTyp (Abstract i)) interfaces)
| _ -> None
};
Field {
name = "possibleTypes";
doc = None;
deprecated = NotDeprecated;
typ = List (NonNullable __type);
args = Arg.[];
lift = Io.ok;
resolve = fun _ t -> match t with
| AnyTyp (Abstract a) ->
Some a.types
| _ -> None
};
Field {
name = "ofType";
doc = None;
deprecated = NotDeprecated;
typ = __type;
args = Arg.[];
lift = Io.ok;
resolve = fun _ t -> match t with
| AnyTyp (NonNullable typ) -> Some (AnyTyp typ)
| AnyTyp (List typ) -> Some (AnyTyp typ)
| AnyArgTyp (Arg.NonNullable typ) -> Some (AnyArgTyp typ)
| AnyArgTyp (Arg.List typ) -> Some (AnyArgTyp typ)
| _ -> None
};
Field {
name = "inputFields";
doc = None;
deprecated = NotDeprecated;
typ = List (NonNullable __input_value);
args = Arg.[];
lift = Io.ok;
resolve = fun _ t -> match t with
| AnyArgTyp (Arg.Object o) ->
Some (args_to_list o.fields)
| _ -> None
};
Field {
name = "enumValues";
doc = None;
deprecated = NotDeprecated;
typ = List (NonNullable __enum_value);
args = Arg.[];
lift = Io.ok;
resolve = fun _ t -> match t with
| AnyTyp (Enum e) -> Some (List.map (fun x -> AnyEnumValue x) e.values)
| AnyArgTyp (Arg.Enum e) -> Some (List.map (fun x -> AnyEnumValue x) e.values)
| _ -> None
}
]
}
and __field : 'ctx. ('ctx, any_field option) typ = Object {
name = "__Field";
doc = None;
abstracts = no_abstracts;
fields = lazy [
Field {
name = "name";
doc = None;
deprecated = NotDeprecated;
typ = NonNullable string;
args = Arg.[];
lift = Io.ok;
resolve = fun _ f -> match f with
| AnyField (Field f) -> f.name
| AnyArgField (Arg.Arg a) -> a.name
| AnyArgField (Arg.DefaultArg a) -> a.name
};
Field {
name = "description";
doc = None;
deprecated = NotDeprecated;
typ = string;
args = Arg.[];
lift = Io.ok;
resolve = fun _ f -> match f with
| AnyField (Field f) -> f.doc
| AnyArgField (Arg.Arg a) -> a.doc
| AnyArgField (Arg.DefaultArg a) -> a.doc
};
Field {
name = "args";
doc = None;
deprecated = NotDeprecated;
typ = NonNullable (List (NonNullable __input_value));
args = Arg.[];
lift = Io.ok;
resolve = fun _ f -> match f with
| AnyField (Field f) -> args_to_list f.args
| AnyArgField _ -> []
};
Field {
name = "type";
doc = None;
deprecated = NotDeprecated;
typ = NonNullable __type;
args = Arg.[];
lift = Io.ok;
resolve = fun _ f -> match f with
| AnyField (Field f) -> AnyTyp f.typ
| AnyArgField (Arg.Arg a) -> AnyArgTyp a.typ
| AnyArgField (Arg.DefaultArg a) -> AnyArgTyp a.typ
};
Field {
name = "isDeprecated";
doc = None;
deprecated = NotDeprecated;
typ = NonNullable bool;
args = Arg.[];
lift = Io.ok;
resolve = fun _ f -> match f with
| AnyField (Field { deprecated = Deprecated _; _ }) -> true
| _ -> false
};
Field {
name = "deprecationReason";
doc = None;
deprecated = NotDeprecated;
typ = string;
args = Arg.[];
lift = Io.ok;
resolve = fun _ f -> match f with
| AnyField (Field { deprecated = Deprecated reason; _ }) -> reason
| _ -> None
}
]
}
let __directive_location = Enum {
name = "__DirectiveLocation";
doc = None;
values = [
{
name="QUERY";
doc=None;
deprecated=NotDeprecated;
value=`Query;
};
{
name="MUTATION";
doc=None;
deprecated=NotDeprecated;
value=`Mutation;
};
{
name="SUBSCRIPTION";
doc=None;
deprecated=NotDeprecated;
value=`Subscription;
};
{
name="FIELD";
doc=None;
deprecated=NotDeprecated;
value=`Field;
};
{
name="FRAGMENT_DEFINITION";
doc=None;
deprecated=NotDeprecated;
value=`Fragment_definition;
};
{
name="FRAGMENT_SPREAD";
doc=None;
deprecated=NotDeprecated;
value=`Fragment_spread;
};
{
name="INLINE_FRAGMENT";
doc=None;
deprecated=NotDeprecated;
value=`Inline_fragment;
};
{
name="VARIABLE_DEFINITION";
doc=None;
deprecated=NotDeprecated;
value=`Variable_definition;
};
]
}
let __directive = Object {
name = "__Directive";
doc = None;
abstracts = no_abstracts;
fields = lazy [
Field {
name = "name";
doc = None;
deprecated = NotDeprecated;
typ = NonNullable string;
args = Arg.[];
lift = Io.ok;
resolve = fun _ (Directive d) -> d.name
};
Field {
name = "description";
doc = None;
deprecated = NotDeprecated;
typ = string;
args = Arg.[];
lift = Io.ok;
resolve = fun _ (Directive d) -> d.doc
};
Field {
name = "locations";
doc = None;
deprecated = NotDeprecated;
typ = NonNullable (List (NonNullable __directive_location));
args = Arg.[];
lift = Io.ok;
resolve = fun _ (Directive d) -> d.locations
};
Field {
name = "args";
doc = None;
deprecated = NotDeprecated;
typ = NonNullable (List (NonNullable __input_value));
args = Arg.[];
lift = Io.ok;
resolve = fun _ (Directive d) -> args_to_list d.args
}
]
}
let __schema : 'ctx. ('ctx, 'ctx schema option) typ = Object {
name = "__Schema";
doc = None;
abstracts = no_abstracts;
fields = lazy [
Field {
name = "types";
doc = None;
deprecated = NotDeprecated;
typ = NonNullable (List (NonNullable __type));
args = Arg.[];
lift = Io.ok;
resolve = fun _ s ->
let types, _ = List.fold_left
(fun memo op ->
match op with
| None -> memo
| Some op -> types ~memo (Object op))
([], StringSet.empty)
[Some s.query; s.mutation; Option.map s.subscription ~f:obj_of_subscription_obj]
in
types
};
Field {
name = "queryType";
doc = None;
deprecated = NotDeprecated;
typ = NonNullable __type;
args = Arg.[];
lift = Io.ok;
resolve = fun _ s -> AnyTyp (Object s.query)
};
Field {
name = "mutationType";
doc = None;
deprecated = NotDeprecated;
typ = __type;
args = Arg.[];
lift = Io.ok;
resolve = fun _ s -> Option.map s.mutation ~f:(fun mut -> AnyTyp (Object mut))
};
Field {
name = "subscriptionType";
doc = None;
deprecated = NotDeprecated;
typ = __type;
args = Arg.[];
lift = Io.ok;
resolve = fun _ s ->
Option.map s.subscription ~f:(fun subs -> AnyTyp (Object (obj_of_subscription_obj subs)))
};
Field {
name = "directives";
doc = None;
deprecated = NotDeprecated;
typ = NonNullable (List (NonNullable __directive));
args = Arg.[];
lift = Io.ok;
resolve = fun _ _ -> []
};
Field {
name = "subscriptionType";
doc = None;
deprecated = NotDeprecated;
typ = __type;
args = Arg.[];
lift = Io.ok;
resolve = fun _ _ -> None
}
]
}
let add_schema_field s =
let schema_field = Field {
name = "__schema";
doc = None;
deprecated = NotDeprecated;
typ = NonNullable __schema;
args = Arg.[];
lift = Io.ok;
resolve = fun _ _ -> s
} in
let fields = lazy (schema_field::(Lazy.force s.query.fields)) in
{ s with query = { s.query with fields } }
end
type variables = (string * Graphql_parser.const_value) list
type execution_order = Serial | Parallel
type 'ctx execution_context = {
variables : variable_map;
fragments : fragment_map;
ctx : 'ctx;
}
type path = [`String of string | `Int of int] list
type error = string * path
type resolve_error = [
| `Resolve_error of error
| `Argument_error of string
| `Validation_error of string
]
type execute_error = [
resolve_error
| `Mutations_not_configured
| `Subscriptions_not_configured
| `No_operation_found
| `Operation_name_required
| `Operation_not_found
]
type 'a response = ('a, Yojson.Basic.json) result
let matches_type_condition type_condition (obj : ('ctx, 'src) obj) =
obj.name = type_condition ||
List.exists (fun (abstract : abstract) -> abstract.name = type_condition) !(obj.abstracts)
let rec should_include_field ctx (directives : Graphql_parser.directive list) =
match directives with
| [] -> Ok true
| { name = "skip"; arguments }::rest ->
eval_directive ctx skip_directive arguments rest
| { name = "include"; arguments }::rest ->
eval_directive ctx include_directive arguments rest
| { name; _ }::_ ->
let err = Format.sprintf "Unknown directive: %s" name in
Error err
and eval_directive ctx (Directive { name; args; resolve; _ }) arguments rest =
let open Rresult in
Arg.eval_arglist ctx.variables ~field_type:"directive" ~field_name:name args arguments resolve >>= function
| `Skip -> Ok false
| `Include -> should_include_field ctx rest
let rec collect_fields : 'ctx execution_context -> ('ctx, 'src) obj -> Graphql_parser.selection list -> (Graphql_parser.field list, string) result =
fun ctx obj fields ->
let open Rresult in
List.map (function
| Graphql_parser.Field field ->
should_include_field ctx field.directives >>| fun include_field ->
if include_field then [field] else []
| Graphql_parser.FragmentSpread spread ->
begin match StringMap.find spread.name ctx.fragments with
| Some { directives; type_condition; selection_set; _ }
when matches_type_condition type_condition obj ->
should_include_field ctx directives >>= fun include_field ->
if include_field then
collect_fields ctx obj selection_set
else Ok []
| _ -> Ok []
end
| Graphql_parser.InlineFragment fragment ->
let matches_type_condition = match fragment.type_condition with
| None -> true
| Some condition -> matches_type_condition condition obj
in
if matches_type_condition then
should_include_field ctx fragment.directives >>= fun include_field ->
if include_field then
collect_fields ctx obj fragment.selection_set
else Ok []
else
Ok []
) fields
|> List.Result.join
|> Rresult.R.map List.concat
let alias_or_name : Graphql_parser.field -> string = fun field ->
match field.alias with
| Some alias -> alias
| None -> field.name
let field_from_object : ('ctx, 'src) obj -> string -> ('ctx, 'src) field option = fun obj field_name ->
List.find (fun (Field field) -> field.name = field_name) (Lazy.force obj.fields)
let field_from_subscription_object = fun obj field_name ->
List.find (fun (SubscriptionField field) -> field.name = field_name) obj.fields
let coerce_or_null : 'a option -> ('a -> (Yojson.Basic.json * error list, 'b) result Io.t) -> (Yojson.Basic.json * error list, 'b) result Io.t =
fun src f ->
match src with
| None -> Io.ok (`Null, [])
| Some src' -> f src'
let map_fields_with_order = function
| Serial -> Io.map_s ~memo:[]
| Parallel -> Io.map_p
let error_to_json ?path msg =
let props = match path with
| Some path -> ["path", `List (List.rev path :> Yojson.Basic.json list)]
| None -> []
in
(`Assoc (("message", `String msg)::props) : Yojson.Basic.json)
let error_response ?data ?path msg =
let errors = "errors", `List [
error_to_json ?path msg
]
in
let data = match data with
| None -> []
| Some data -> ["data", data]
in
`Assoc (errors :: data)
let rec present : type ctx src. ctx execution_context -> src -> Graphql_parser.field -> (ctx, src) typ -> path -> (Yojson.Basic.json * error list, [> resolve_error]) result Io.t =
fun ctx src query_field typ path ->
match typ with
| Scalar s -> coerce_or_null src (fun x -> Io.ok (s.coerce x, []))
| List t ->
coerce_or_null src (fun src' ->
List.mapi (fun i x -> present ctx x query_field t ((`Int i)::path)) src'
|> Io.all
|> Io.map ~f:List.Result.join
|> Io.Result.map ~f:(fun xs -> (`List (List.map fst xs), List.map snd xs |> List.concat))
)
| NonNullable t -> present ctx (Some src) query_field t path
| Object o ->
coerce_or_null src (fun src' ->
match collect_fields ctx o query_field.selection_set with
| Ok fields -> resolve_fields ctx src' o fields path
| Error e -> Io.error (`Argument_error e))
| Enum e ->
coerce_or_null src (fun src' ->
match List.find (fun enum_value -> src' == enum_value.value) e.values with
| Some enum_value -> Io.ok (`String enum_value.name, [])
| None -> Io.ok (`Null, [])
)
| Abstract _ ->
coerce_or_null src (fun (AbstractValue (typ', src')) ->
present ctx (Some src') query_field typ' path
)
and resolve_field : type ctx src. ctx execution_context -> src -> Graphql_parser.field -> (ctx, src) field -> path -> ((string * Yojson.Basic.json) * error list, [> resolve_error]) result Io.t =
fun ctx src query_field (Field field) path ->
let open Io.Infix in
let name = alias_or_name query_field in
let path' = (`String name)::path in
let resolve_info = {
ctx = ctx.ctx;
field = query_field;
fragments = ctx.fragments;
variables = ctx.variables;
} in
let resolver = field.resolve resolve_info src in
match Arg.eval_arglist ctx.variables ~field_name:field.name field.args query_field.arguments resolver with
| Ok unlifted_value ->
let lifted_value =
field.lift unlifted_value
|> Io.Result.map_error ~f:(fun err -> `Resolve_error (err, path')) >>=? fun resolved ->
present ctx resolved query_field field.typ path'
in
lifted_value >>| (function
| Ok (value, errors) ->
Ok ((name, value), errors)
| Error (`Argument_error _)
| Error (`Validation_error _) as error ->
error
| Error (`Resolve_error err) as error ->
match field.typ with
| NonNullable _ ->
error
| _ ->
Ok ((name, `Null), [err])
)
| Error err ->
Io.error (`Argument_error err)
and resolve_fields : type ctx src. ctx execution_context -> ?execution_order:execution_order -> src -> (ctx, src) obj -> Graphql_parser.field list -> path -> (Yojson.Basic.json * error list, [> resolve_error]) result Io.t =
fun ctx ?execution_order:(execution_order=Parallel) src obj fields path ->
map_fields_with_order execution_order (fun (query_field : Graphql_parser.field) ->
let name = alias_or_name query_field in
if query_field.name = "__typename" then
Io.ok ((name, `String obj.name), [])
else
match field_from_object obj query_field.name with
| Some field ->
resolve_field ctx src query_field field path
| None ->
let err = Printf.sprintf "Field '%s' is not defined on type '%s'" query_field.name obj.name in
Io.error (`Validation_error err)
) fields
|> Io.map ~f:List.Result.join
|> Io.Result.map ~f:(fun xs -> (`Assoc (List.map fst xs), List.map snd xs |> List.concat))
let data_to_json = function
| data, [] -> `Assoc ["data", data]
| data, errors ->
let errors = List.map (fun (msg, path) -> error_to_json ~path msg) errors in
`Assoc [
"errors", `List errors;
"data", data;
]
let to_response = function
| Ok _ as res -> res
| Error `No_operation_found ->
Error (error_response "No operation found")
| Error `Operation_not_found ->
Error (error_response "Operation not found")
| Error `Operation_name_required ->
Error (error_response "Operation name required")
| Error `Subscriptions_not_configured ->
Error (error_response "Subscriptions not configured")
| Error `Mutations_not_configured ->
Error (error_response "Mutations not configured")
| Error (`Validation_error msg) ->
Error (error_response msg)
| Error (`Argument_error msg) ->
Error (error_response ~data:`Null msg)
| Error (`Resolve_error (msg, path)) ->
Error (error_response ~data:`Null ~path msg)
let subscribe : type ctx. ctx execution_context -> ctx subscription_field -> Graphql_parser.field -> (Yojson.Basic.json response Io.Stream.t, [> resolve_error]) result Io.t
=
fun ctx (SubscriptionField subs_field) field ->
let open Io.Infix in
let name = alias_or_name field in
let path = [`String name] in
let resolve_info = {
ctx = ctx.ctx;
field;
fragments = ctx.fragments;
variables = ctx.variables
} in
let resolver = subs_field.resolve resolve_info in
match Arg.eval_arglist ctx.variables ~field_name:subs_field.name subs_field.args field.arguments resolver with
| Ok result ->
result
|> Io.Result.map ~f:(fun source_stream ->
Io.Stream.map source_stream (fun value ->
present ctx value field subs_field.typ path
|> Io.Result.map ~f:(fun (data, errors) ->
data_to_json (`Assoc [name, data], errors)
)
>>| to_response
)
)
|> Io.Result.map_error ~f:(fun err ->
`Resolve_error (err, path)
)
| Error err -> Io.error (`Argument_error err)
let execute_operation : 'ctx schema -> 'ctx execution_context -> Graphql_parser.operation -> ([ `Response of Yojson.Basic.json | `Stream of Yojson.Basic.json response Io.Stream.t], [> execute_error]) result Io.t =
fun schema ctx operation ->
let open Io.Infix in
match operation.optype with
| Graphql_parser.Query ->
let query = schema.query in
Io.return (collect_fields ctx query operation.selection_set)
|> Io.Result.map_error ~f:(fun e -> `Argument_error e) >>=? fun fields ->
(resolve_fields ctx () query fields [] : (Yojson.Basic.json * error list, resolve_error) result Io.t :> (Yojson.Basic.json * error list, [> execute_error]) result Io.t)
|> Io.Result.map ~f:(fun data_errs -> `Response (data_to_json data_errs))
| Graphql_parser.Mutation ->
begin match schema.mutation with
| None -> Io.error `Mutations_not_configured
| Some mut ->
Io.return (collect_fields ctx mut operation.selection_set)
|> Io.Result.map_error ~f:(fun e -> `Argument_error e) >>=? fun fields ->
(resolve_fields ~execution_order:Serial ctx () mut fields [] : (Yojson.Basic.json * error list, resolve_error) result Io.t :> (Yojson.Basic.json * error list, [> execute_error]) result Io.t)
|> Io.Result.map ~f:(fun data_errs -> `Response (data_to_json data_errs))
end
| Graphql_parser.Subscription ->
begin match schema.subscription with
| None -> Io.error `Subscriptions_not_configured
| Some subs ->
Io.return (collect_fields ctx (obj_of_subscription_obj subs) operation.selection_set)
|> Io.Result.map_error ~f:(fun e -> `Argument_error e) >>=? fun fields ->
begin match fields with
| [field] ->
(match field_from_subscription_object subs field.name with
| Some subscription_field ->
(subscribe ctx subscription_field field : ((Yojson.Basic.json, Yojson.Basic.json) result Io.Stream.t, resolve_error) result Io.t :> ((Yojson.Basic.json, Yojson.Basic.json) result Io.Stream.t, [> execute_error]) result Io.t)
|> Io.Result.map ~f:(fun stream -> `Stream stream)
| None -> Io.ok (`Response (`Assoc [(alias_or_name field, `Null)])))
| _ -> Io.error (`Validation_error "Subscriptions only allow exactly one selection for the operation.")
end
end
let collect_fragments doc =
List.fold_left (fun memo -> function
| Graphql_parser.Operation _ -> memo
| Graphql_parser.Fragment f -> StringMap.add f.name f memo
) StringMap.empty doc
exception FragmentCycle of string list
let rec validate_fragments fragment_map =
try
StringMap.iter (fun name _ ->
validate_fragment fragment_map StringSet.empty name
) fragment_map;
Ok fragment_map
with FragmentCycle fragment_names ->
let cycle = String.concat ", " fragment_names in
let err = Format.sprintf "Fragment cycle detected: %s" cycle in
Error (`Validation_error err)
and validate_fragment (fragment_map : fragment_map) visited name =
match StringMap.find name fragment_map with
| None -> ()
| Some fragment when StringSet.mem fragment.name visited ->
raise (FragmentCycle (StringSet.elements visited))
| Some fragment ->
let visited' = StringSet.add fragment.name visited in
List.iter (validate_fragment_selection fragment_map visited') fragment.selection_set
and validate_fragment_selection fragment_map visited selection =
match selection with
| Graphql_parser.Field field ->
List.iter (validate_fragment_selection fragment_map visited) field.selection_set
| InlineFragment inline_fragment ->
List.iter (validate_fragment_selection fragment_map visited) inline_fragment.selection_set
| FragmentSpread fragment_spread ->
validate_fragment fragment_map visited fragment_spread.name
let collect_and_validate_fragments doc =
let fragments = collect_fragments doc in
validate_fragments fragments
let collect_operations doc =
List.fold_left (fun memo -> function
| Graphql_parser.Operation op -> op::memo
| Graphql_parser.Fragment _ -> memo
) [] doc
let select_operation ?operation_name doc =
let operations = collect_operations doc in
match operation_name, operations with
| _, [] -> Error `No_operation_found
| None, [op] -> Ok op
| None, _::_ -> Error `Operation_name_required
| Some name, ops ->
try
Ok (List.find_exn (fun op -> op.Graphql_parser.name = Some name) ops)
with Not_found ->
Error `Operation_not_found
let execute schema ctx ?variables:(variables=[]) ?operation_name doc =
let open Io.Infix in
let execute' schema ctx doc =
Io.return (collect_and_validate_fragments doc) >>=? fun fragments ->
let variables = List.fold_left (fun memo (name, value) -> StringMap.add name value memo) StringMap.empty variables in
let execution_ctx = { fragments; ctx; variables } in
let schema' = Introspection.add_schema_field schema in
Io.return (select_operation ?operation_name doc) >>=? fun op ->
execute_operation schema' execution_ctx op
in
execute' schema ctx doc >>| to_response
end