-
Notifications
You must be signed in to change notification settings - Fork 25
/
schema.scala
1283 lines (1101 loc) · 44.1 KB
/
schema.scala
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) 2016-2020 Association of Universities for Research in Astronomy, Inc. (AURA)
// For license information see LICENSE or https://opensource.org/licenses/BSD-3-Clause
package edu.gemini.grackle
import cats.data.{Ior, NonEmptyChain}
import cats.parse.Parser
import cats.implicits._
import io.circe.Json
import org.tpolecat.sourcepos.SourcePos
import Ast.{EnumTypeDefinition, FieldDefinition, InterfaceTypeDefinition, ObjectTypeDefinition, TypeDefinition}
import QueryInterpreter.{mkError, mkErrorResult, mkOneError}
import ScalarType._
import Value._
/**
* Representation of a GraphQL schema
*
* A `Schema` is a collection of type and directive declarations.
*/
trait Schema {
def pos: SourcePos
/** The types defined by this `Schema`. */
def types: List[NamedType]
/** The directives defined by this `Schema`. */
def directives: List[Directive]
/** A reference by name to a type defined by this `Schema`.
*
* `TypeRef`s refer to types defined in this schema by name and hence
* can be used as part of mutually recursive type definitions.
*/
def ref(tpnme: String): TypeRef = new TypeRef(this, tpnme)
/**
* Alias for `ref` for use within constructors of concrete
* `Schema` values.
*/
protected def TypeRef(tpnme: String): TypeRef = ref(tpnme)
/**
* The default type of a GraphQL schema
*
* Unless a type named `"Schema"` is explicitly defined as part of
* this `Schema` a definition of the form,
*
* ```
* type Schema {
* query: Query!
* mutation: Mutation
* subscription: Subscription
* }
* ```
*
* is used.
*/
def defaultSchemaType: NamedType = {
def mkRootDef(fieldName: String)(tpe: NamedType): Field =
Field(fieldName, None, Nil, tpe, false, None)
ObjectType(
name = "Schema",
description = None,
fields =
List(
definition("Query").map(mkRootDef("query")),
definition("Mutation").map(mkRootDef("mutation")),
definition("Subscription").map(mkRootDef("subscription"))
).flatten,
interfaces = Nil
)
}
/**
* Look up by name a type defined in this `Schema`.
*
* Yields the type, if defined, `None` otherwise.
*/
def definition(name: String): Option[NamedType] =
typeIndex.get(name).orElse(ScalarType(name)).map(_.dealias)
private lazy val typeIndex = types.map(tpe => (tpe.name, tpe)).toMap
def ref(tp: Type): Option[TypeRef] = tp match {
case nt: NamedType if types.exists(_.name == nt.name) => Some(ref(nt.name))
case _ => None
}
/**
* The schema type.
*
* Either the explicitly defined type named `"Schema"` or the default
* schema type if not defined.
*/
def schemaType: NamedType = definition("Schema").getOrElse(defaultSchemaType)
/** The type of queries defined by this `Schema`*/
def queryType: NamedType = schemaType.field("query").flatMap(_.asNamed).get
/** The type of mutations defined by this `Schema`*/
def mutationType: Option[NamedType] = schemaType.field("mutation").flatMap(_.asNamed)
/** The type of subscriptions defined by this `Schema`*/
def subscriptionType: Option[NamedType] = schemaType.field("subscription").flatMap(_.asNamed)
/** True if the supplied type is one of the Query, Mutation or Subscription root types, false otherwise */
def isRootType(tpe: Type): Boolean =
tpe =:= queryType || mutationType.map(_ =:= tpe).getOrElse(false) || subscriptionType.map(_ =:= tpe).getOrElse(false)
/** Are the supplied alternatives exhaustive for `tp` */
def exhaustive(tp: Type, branches: List[Type]): Boolean = {
types.forall {
case o: ObjectType => !(o <:< tp) || branches.exists(b => o <:< b)
case _ => true
}
}
override def toString = SchemaRenderer.renderSchema(this)
}
object Schema {
def apply(schemaText: String)(implicit pos: SourcePos): Result[Schema] =
SchemaParser.parseText(schemaText)
}
/**
* A GraphQL type definition.
*/
sealed trait Type extends Product {
/**
* Is this type equivalent to `other`.
*
* Note that plain `==` will distinguish types from type aliases,
* which is typically not desirable, so `=:=` is usually the
* most appropriate comparison operator.
*/
def =:=(other: Type): Boolean = (this eq other) || (dealias == other.dealias)
/** `true` if this type is a subtype of `other`. */
def <:<(other: Type): Boolean =
(this.dealias, other.dealias) match {
case (tp1, tp2) if tp1 == tp2 => true
case (tp1, UnionType(_, _, members)) => members.exists(tp1 <:< _.dealias)
case (ObjectType(_, _, _, interfaces), tp2) => interfaces.exists(_.dealias == tp2)
case _ => false
}
def nominal_=:=(other: Type): Boolean =
this =:= other ||
((this.dealias, other.dealias) match {
case (nt1: NamedType, nt2: NamedType) => nt1.name == nt2.name
case _ => false
})
/**
* Yield the type of the field of this type named `fieldName` or
* `None` if there is no such field.
*/
def field(fieldName: String): Option[Type] = this match {
case NullableType(tpe) => tpe.field(fieldName)
case TypeRef(_, _) if exists => dealias.field(fieldName)
case ObjectType(_, _, fields, _) => fields.find(_.name == fieldName).map(_.tpe)
case InterfaceType(_, _, fields, _) => fields.find(_.name == fieldName).map(_.tpe)
case _ => None
}
/** `true` if this type has a field named `fieldName`, false otherwise. */
def hasField(fieldName: String): Boolean =
field(fieldName).isDefined
/**
* `true` if this type has a field named `fieldName` which is undefined in
* some interface it implements
*/
def variantField(fieldName: String): Boolean =
underlyingObject match {
case Some(ObjectType(_, _, _, interfaces)) =>
hasField(fieldName) && interfaces.exists(!_.hasField(fieldName))
case _ => false
}
def withField[T](fieldName: String)(body: Type => Result[T]): Result[T] =
field(fieldName).map(body).getOrElse(mkErrorResult(s"Unknown field '$fieldName' in '$this'"))
/**
* Yield the type of the field at the end of the path `fns` starting
* from this type, or `None` if there is no such field.
*/
def path(fns: List[String]): Option[Type] = (fns, this) match {
case (Nil, _) => Some(this)
case (_, ListType(tpe)) => tpe.path(fns)
case (_, NullableType(tpe)) => tpe.path(fns)
case (_, TypeRef(_, _)) => dealias.path(fns)
case (fieldName :: rest, ObjectType(_, _, fields, _)) =>
fields.find(_.name == fieldName).flatMap(_.tpe.path(rest))
case (fieldName :: rest, InterfaceType(_, _, fields, _)) =>
fields.find(_.name == fieldName).flatMap(_.tpe.path(rest))
case _ => None
}
/**
* Does the path `fns` from this type specify multiple values.
*
* `true` if navigating through the path `fns` from this type
* might specify 0 or more values. This will be the case if the
* path passes through at least one field of a List type.
*/
def pathIsList(fns: List[String]): Boolean = (fns, this) match {
case (Nil, _) => this.isList
case (_, _: ListType) => true
case (_, NullableType(tpe)) => tpe.pathIsList(fns)
case (_, TypeRef(_, _)) => dealias.pathIsList(fns)
case (fieldName :: rest, ObjectType(_, _, fields, _)) =>
fields.find(_.name == fieldName).map(_.tpe.pathIsList(rest)).getOrElse(false)
case (fieldName :: rest, InterfaceType(_, _, fields, _)) =>
fields.find(_.name == fieldName).map(_.tpe.pathIsList(rest)).getOrElse(false)
case _ => false
}
/**
* Does the path `fns` from this type specify a nullable type.
*
* `true` if navigating through the path `fns` from this type
* might specify an optional value. This will be the case if the
* path passes through at least one field of a nullable type.
*/
def pathIsNullable(fns: List[String]): Boolean = (fns, this) match {
case (Nil, _) => false
case (_, ListType(tpe)) => tpe.pathIsNullable(fns)
case (_, _: NullableType) => true
case (_, TypeRef(_, _)) => dealias.pathIsNullable(fns)
case (fieldName :: rest, ObjectType(_, _, fields, _)) =>
fields.find(_.name == fieldName).map(_.tpe.pathIsNullable(rest)).getOrElse(false)
case (fieldName :: rest, InterfaceType(_, _, fields, _)) =>
fields.find(_.name == fieldName).map(_.tpe.pathIsNullable(rest)).getOrElse(false)
case _ => false
}
/** Strip off aliases */
def dealias: Type = this
/** true if a non-TypeRef or a TypeRef to a defined type */
def exists: Boolean = true
/** Is this type nullable? */
def isNullable: Boolean = this match {
case NullableType(_) => true
case _ => false
}
/** This type if it is nullable, `Nullable(this)` otherwise. */
def nullable: Type = this match {
case t: NullableType => t
case t => NullableType(t)
}
/**
* A non-nullable version of this type.
*
* If this type is nullable, yield the non-nullable underlying
* type. Otherwise yield this type.
*/
def nonNull: Type = this match {
case NullableType(tpe) => tpe.nonNull
case _ => this
}
/** Is this type a list. */
def isList: Boolean = this match {
case ListType(_) => true
case _ => false
}
/**
* The element type of this type.
*
* If this type is is a list, yield the non-list underlying type.
* Otherwise yield `None`.
*/
def item: Option[Type] = this match {
case NullableType(tpe) => tpe.item
case ListType(tpe) => Some(tpe)
case _ => None
}
/** This type if it is a (nullable) list, `ListType(this)` otherwise. */
def list: Type = this match {
case l: ListType => l
case NullableType(tpe) => NullableType(tpe.list)
case tpe => ListType(tpe)
}
def underlying: Type = this match {
case NullableType(tpe) => tpe.underlying
case ListType(tpe) => tpe.underlying
case _: TypeRef => dealias.underlying
case _ => this
}
/**
* Yield the object type underlying this type.
*
* Strip off all aliases, nullability and enclosing list types until
* an underlying object type is reached, in which case yield it, or a
* non-object type which isn't further reducible is reached, in which
* case yield `None`.
*/
def underlyingObject: Option[Type] = this match {
case NullableType(tpe) => tpe.underlyingObject
case ListType(tpe) => tpe.underlyingObject
case _: TypeRef => dealias.underlyingObject
case o: ObjectType => Some(o)
case i: InterfaceType => Some(i)
case u: UnionType => Some(u)
case _ => None
}
/**
* Yield the type of the field named `fieldName` of the object type
* underlying this type.
*
* Strip off all aliases, nullability and enclosing list types until
* an underlying object type is reached which has a field named
* `fieldName`, in which case yield the type of that field; if there
* is no such field, yields `None`.
*/
def underlyingField(fieldName: String): Option[Type] = this match {
case NullableType(tpe) => tpe.underlyingField(fieldName)
case ListType(tpe) => tpe.underlyingField(fieldName)
case TypeRef(_, _) => dealias.underlyingField(fieldName)
case ObjectType(_, _, fields, _) => fields.find(_.name == fieldName).map(_.tpe)
case InterfaceType(_, _, fields, _) => fields.find(_.name == fieldName).map(_.tpe)
case _ => None
}
def withUnderlyingField[T](fieldName: String)(body: Type => Result[T]): Result[T] =
underlyingObject.toRightIor(mkOneError(s"$this is not an object or interface type")).flatMap(_.withField(fieldName)(body))
/** Is this type a leaf type?
*
* `true` if after stripping of aliases the underlying type a scalar or an
* enum, `false` otherwise.
*/
def isLeaf: Boolean = this match {
case TypeRef(_, _) => dealias.isLeaf
case _: ScalarType => true
case _: EnumType => true
case _ => false
}
/**
* If the underlying type of this type is a scalar or an enum then yield it
* otherwise yield `None`.
*/
def asLeaf: Option[Type] = this match {
case TypeRef(_, _) => dealias.asLeaf
case _: ScalarType => Some(this)
case _: EnumType => Some(this)
case _ => None
}
/**
* Is the underlying of this type a leaf type?
*
* Strip off all aliases, nullability and enclosing list types until
* an underlying leaf type is reached, in which case yield true, or an
* a object, interface or union type which is reached, in which case
* yield false.
*/
def isUnderlyingLeaf: Boolean = this match {
case NullableType(tpe) => tpe.isUnderlyingLeaf
case ListType(tpe) => tpe.isUnderlyingLeaf
case _: TypeRef => dealias.isUnderlyingLeaf
case (_: ObjectType)|(_: InterfaceType)|(_: UnionType) => false
case _ => true
}
/**
* Yield the leaf type underlying this type.
*
* Strip off all aliases, nullability and enclosing list types until
* an underlying leaf type is reached, in which case yield it, or an
* a object, interface or union type which is reached, in which case
* yield `None`.
*/
def underlyingLeaf: Option[Type] = this match {
case NullableType(tpe) => tpe.underlyingLeaf
case ListType(tpe) => tpe.underlyingLeaf
case _: TypeRef => dealias.underlyingLeaf
case (_: ObjectType)|(_: InterfaceType)|(_: UnionType) => None
case tpe => Some(tpe)
}
def withModifiersOf(tpe: Type): Type = {
def loop(rtpe: Type, tpe: Type): Type = tpe match {
case NullableType(tpe) => loop(NullableType(rtpe), tpe)
case ListType(tpe) => loop(ListType(rtpe), tpe)
case _ => rtpe
}
loop(this, tpe)
}
def isNamed: Boolean = false
def asNamed: Option[NamedType] = None
def isInterface: Boolean = false
def isUnion: Boolean = false
def /(pathElement: String): Path =
Path.from(this) / pathElement
}
// Move all below into object Type?
/** A type with a schema-defined name.
*
* This includes object types, inferface types and enums.
*/
sealed trait NamedType extends Type {
/** The name of this type */
def name: String
override def dealias: NamedType = this
override def isNamed: Boolean = true
override def asNamed: Option[NamedType] = Some(this)
def description: Option[String]
override def toString: String = name
}
/**
* A by name reference to a type defined in `schema`.
*/
case class TypeRef(schema: Schema, name: String) extends NamedType {
override lazy val dealias: NamedType = schema.definition(name).getOrElse(this)
override lazy val exists: Boolean = schema.definition(name).isDefined
def description: Option[String] = dealias.description
}
/**
* Represents scalar types such as Int, String, and Boolean. Scalars cannot have fields.
*
* @see https://facebook.github.io/graphql/draft/#sec-Scalar
*/
case class ScalarType(
name: String,
description: Option[String]
) extends Type with NamedType {
import ScalarType._
/** True if this is one of the five built-in Scalar types defined in the GraphQL Specification. */
def isBuiltIn: Boolean =
this match {
case IntType |
FloatType |
StringType |
BooleanType |
IDType => true
case _ => false
}
}
object ScalarType {
def apply(tpnme: String): Option[ScalarType] = tpnme match {
case "Int" => Some(IntType)
case "Float" => Some(FloatType)
case "String" => Some(StringType)
case "Boolean" => Some(BooleanType)
case "ID" => Some(IDType)
case _ => None
}
val IntType = ScalarType(
name = "Int",
description =
Some(
"""|The Int scalar type represents a signed 32‐bit numeric non‐fractional value.
|Response formats that support a 32‐bit integer or a number type should use that
|type to represent this scalar.
""".stripMargin.trim
)
)
val FloatType = ScalarType(
name = "Float",
description =
Some(
"""|The Float scalar type represents signed double‐precision fractional values as
|specified by IEEE 754. Response formats that support an appropriate
|double‐precision number type should use that type to represent this scalar.
""".stripMargin.trim
)
)
val StringType = ScalarType(
name = "String",
description =
Some(
"""|The String scalar type represents textual data, represented as UTF‐8 character
|sequences. The String type is most often used by GraphQL to represent free‐form
|human‐readable text.
""".stripMargin.trim
)
)
val BooleanType = ScalarType(
name = "Boolean",
description =
Some(
"""|The Boolean scalar type represents true or false. Response formats should use a
|built‐in boolean type if supported; otherwise, they should use their
|representation of the integers 1 and 0.
""".stripMargin.trim
)
)
val IDType = ScalarType(
name = "ID",
description =
Some(
"""|The ID scalar type represents a unique identifier, often used to refetch an
|object or as the key for a cache. The ID type is serialized in the same way as a
|String; however, it is not intended to be human‐readable.
""".stripMargin.trim
)
)
val AttributeType = ScalarType(
name = "InternalAttribute",
description = None
)
}
/**
* A type with fields.
*
* This includes object types and inferface types.
*/
sealed trait TypeWithFields extends NamedType {
def fields: List[Field]
def fieldInfo(name: String): Option[Field] = fields.find(_.name == name)
}
/**
* Interfaces are an abstract type where there are common fields declared. Any type that
* implements an interface must define all the fields with names and types exactly matching.
*
* @see https://facebook.github.io/graphql/draft/#sec-Interface
*/
case class InterfaceType(
name: String,
description: Option[String],
fields: List[Field],
interfaces: List[NamedType]
) extends Type with TypeWithFields {
override def isInterface: Boolean = true
}
/**
* Object types represent concrete instantiations of sets of fields.
*
* @see https://facebook.github.io/graphql/draft/#sec-Object
*/
case class ObjectType(
name: String,
description: Option[String],
fields: List[Field],
interfaces: List[NamedType]
) extends Type with TypeWithFields
/**
* Unions are an abstract type where no common fields are declared. The possible types of a union
* are explicitly listed out in elements. Types can be made parts of unions without
* modification of that type.
*
* @see https://facebook.github.io/graphql/draft/#sec-Union
*/
case class UnionType(
name: String,
description: Option[String],
members: List[NamedType]
) extends Type with NamedType {
override def isUnion: Boolean = true
override def toString: String = members.mkString("|")
}
/**
* Enums are special scalars that can only have a defined set of values.
*
* @see https://facebook.github.io/graphql/draft/#sec-Enum
*/
case class EnumType(
name: String,
description: Option[String],
enumValues: List[EnumValue]
) extends Type with NamedType {
def hasValue(name: String): Boolean = enumValues.exists(_.name == name)
def value(name: String): Option[EnumValue] = enumValues.find(_.name == name)
}
/**
* The `EnumValue` type represents one of possible values of an enum.
*
* @see https://facebook.github.io/graphql/draft/#sec-The-__EnumValue-Type
*/
case class EnumValue(
name: String,
description: Option[String],
isDeprecated: Boolean = false,
deprecationReason: Option[String] = None
)
/**
* Input objects are composite types used as inputs into queries defined as a list of named input
* values.
*
* @see https://facebook.github.io/graphql/draft/#sec-Input-Object
*/
case class InputObjectType(
name: String,
description: Option[String],
inputFields: List[InputValue]
) extends Type with NamedType {
def inputFieldInfo(name: String): Option[InputValue] = inputFields.find(_.name == name)
}
/**
* Lists represent sequences of values in GraphQL. A List type is a type modifier: it wraps
* another type instance in the ofType field, which defines the type of each item in the list.
*
* @see https://facebook.github.io/graphql/draft/#sec-Type-Kinds.List
*/
case class ListType(
ofType: Type
) extends Type {
override def toString: String = s"[$ofType]"
}
/**
* A Non‐null type is a type modifier: it wraps another type instance in the `ofType` field.
* Non‐null types do not allow null as a response, and indicate required inputs for arguments
* and input object fields.
*
* @see https://facebook.github.io/graphql/draft/#sec-Type-Kinds.Non-Null
*/
case class NullableType(
ofType: Type
) extends Type {
override def toString: String = s"$ofType?"
}
/**
* The `Field` type represents each field in an Object or Interface type.
*
* @see https://facebook.github.io/graphql/draft/#sec-The-__Field-Type
*/
case class Field(
name: String,
description: Option[String],
args: List[InputValue],
tpe: Type,
isDeprecated: Boolean,
deprecationReason: Option[String]
)
/**
* @param defaultValue a String encoding (using the GraphQL language) of the default value used by
* this input value in the condition a value is not provided at runtime.
*/
case class InputValue(
name: String,
description: Option[String],
tpe: Type,
defaultValue: Option[Value]
)
sealed trait Value
object Value {
case class IntValue(value: Int) extends Value
case class FloatValue(value: Double) extends Value
case class StringValue(value: String) extends Value
case class BooleanValue(value: Boolean) extends Value
case class IDValue(value: String) extends Value
case class UntypedEnumValue(name: String) extends Value
case class TypedEnumValue(value: EnumValue) extends Value
case class UntypedVariableValue(name: String) extends Value
case class ListValue(elems: List[Value]) extends Value
case class ObjectValue(fields: List[(String, Value)]) extends Value
case object NullValue extends Value
case object AbsentValue extends Value
object StringListValue {
def apply(ss: List[String]): Value =
ListValue(ss.map(StringValue(_)))
def unapply(value: Value): Option[List[String]] =
value match {
case ListValue(l) => l.traverse {
case StringValue(s) => Some(s)
case _ => None
}
case _ => None
}
}
def checkValue(iv: InputValue, value: Option[Value]): Result[Value] =
(iv.tpe.dealias, value) match {
case (_, None) if iv.defaultValue.isDefined =>
iv.defaultValue.get.rightIor
case (_: NullableType, None) =>
AbsentValue.rightIor
case (_: NullableType, Some(AbsentValue)) =>
AbsentValue.rightIor
case (_: NullableType, Some(NullValue)) =>
NullValue.rightIor
case (NullableType(tpe), Some(_)) =>
checkValue(iv.copy(tpe = tpe), value)
case (IntType, Some(value: IntValue)) =>
value.rightIor
case (FloatType, Some(value: FloatValue)) =>
value.rightIor
case (StringType, Some(value: StringValue)) =>
value.rightIor
case (BooleanType, Some(value: BooleanValue)) =>
value.rightIor
// Custom Scalars
case (s @ ScalarType(_, _), Some(value: IntValue)) if !s.isBuiltIn =>
value.rightIor
case (s @ ScalarType(_, _), Some(value: FloatValue)) if !s.isBuiltIn =>
value.rightIor
case (s @ ScalarType(_, _), Some(value: StringValue)) if !s.isBuiltIn =>
value.rightIor
case (s @ ScalarType(_, _), Some(value: BooleanValue)) if !s.isBuiltIn =>
value.rightIor
case (IDType, Some(value: IDValue)) =>
value.rightIor
case (IDType, Some(StringValue(s))) =>
IDValue(s).rightIor
case (IDType, Some(IntValue(i))) =>
IDValue(i.toString).rightIor
case (_: EnumType, Some(value: TypedEnumValue)) =>
value.rightIor
case (e: EnumType, Some(UntypedEnumValue(name))) if e.hasValue(name) =>
TypedEnumValue(e.value(name).get).rightIor
case (ListType(tpe), Some(ListValue(arr))) =>
arr.traverse { elem =>
checkValue(iv.copy(tpe = tpe, defaultValue = None), Some(elem))
}.map(ListValue.apply)
case (InputObjectType(nme, _, ivs), Some(ObjectValue(fs))) =>
val obj = fs.toMap
val unknownFields = fs.map(_._1).filterNot(f => ivs.exists(_.name == f))
if (unknownFields.nonEmpty)
mkErrorResult(s"Unknown field(s) ${unknownFields.map(s => s"'$s'").mkString("", ", ", "")} in input object value of type ${nme}")
else
ivs.traverse(iv => checkValue(iv, obj.get(iv.name)).map(v => (iv.name, v))).map(ObjectValue.apply)
case (_: ScalarType, Some(value)) => value.rightIor
case (tpe, Some(value)) => mkErrorResult(s"Expected $tpe found '$value' for '${iv.name}'")
case (tpe, None) => mkErrorResult(s"Value of type $tpe required for '${iv.name}'")
}
def checkVarValue(iv: InputValue, value: Option[Json]): Result[Value] = {
import JsonExtractor._
(iv.tpe.dealias, value) match {
case (_, None) if iv.defaultValue.isDefined =>
iv.defaultValue.get.rightIor
case (_: NullableType, None) =>
AbsentValue.rightIor
case (_: NullableType, Some(jsonNull(_))) =>
NullValue.rightIor
case (NullableType(tpe), Some(_)) =>
checkVarValue(iv.copy(tpe = tpe), value)
case (IntType, Some(jsonInt(value))) =>
IntValue(value).rightIor
case (FloatType, Some(jsonDouble(value))) =>
FloatValue(value).rightIor
case (StringType, Some(jsonString(value))) =>
StringValue(value).rightIor
case (BooleanType, Some(jsonBoolean(value))) =>
BooleanValue(value).rightIor
case (IDType, Some(jsonInt(value))) =>
IDValue(value.toString).rightIor
// Custom scalars
case (s @ ScalarType(_, _), Some(jsonInt(value))) if !s.isBuiltIn =>
IntValue(value).rightIor
case (s @ ScalarType(_, _), Some(jsonDouble(value))) if !s.isBuiltIn =>
FloatValue(value).rightIor
case (s @ ScalarType(_, _), Some(jsonString(value))) if !s.isBuiltIn =>
StringValue(value).rightIor
case (s @ ScalarType(_, _), Some(jsonBoolean(value))) if !s.isBuiltIn =>
BooleanValue(value).rightIor
case (IDType, Some(jsonString(value))) =>
IDValue(value).rightIor
case (e: EnumType, Some(jsonString(name))) if e.hasValue(name) =>
TypedEnumValue(e.value(name).get).rightIor
case (ListType(tpe), Some(jsonArray(arr))) =>
arr.traverse { elem =>
checkVarValue(iv.copy(tpe = tpe, defaultValue = None), Some(elem))
}.map(vs => ListValue(vs.toList))
case (InputObjectType(nme, _, ivs), Some(jsonObject(obj))) =>
val unknownFields = obj.keys.filterNot(f => ivs.exists(_.name == f))
if (unknownFields.nonEmpty)
mkErrorResult(s"Unknown field(s) ${unknownFields.map(s => s"'$s'").mkString("", ", ", "")} in input object value of type ${nme}")
else
ivs.traverse(iv => checkVarValue(iv, obj(iv.name)).map(v => (iv.name, v))).map(ObjectValue.apply)
case (_: ScalarType, Some(jsonString(value))) => StringValue(value).rightIor
case (tpe, Some(value)) => mkErrorResult(s"Expected $tpe found '$value' for '${iv.name}'")
case (tpe, None) => mkErrorResult(s"Value of type $tpe required for '${iv.name}'")
}
}
}
/**
* The `Directive` type represents a Directive that a server supports.
*
* @see https://facebook.github.io/graphql/draft/#sec-The-__Directive-Type
*/
case class Directive(
name: String,
description: Option[String],
locations: List[Ast.DirectiveLocation],
args: List[InputValue]
)
/**
* GraphQL schema parser
*/
object SchemaParser {
import Ast.{Directive => DefinedDirective, Type => _, Value => _, _}
import OperationType._
/**
* Parse a query String to a query algebra term.
*
* Yields a Query value on the right and accumulates errors on the left.
*/
def parseText(text: String)(implicit pos: SourcePos): Result[Schema] = {
def toResult[T](pr: Either[Parser.Error, T]): Result[T] =
Ior.fromEither(pr).leftMap(e => mkOneError(e.expected.toList.mkString(",")))
for {
doc <- toResult(GraphQLParser.Document.parseAll(text))
query <- parseDocument(doc)
} yield query
}
def parseDocument(doc: Document)(implicit sourcePos: SourcePos): Result[Schema] = {
// explicit Schema type, if any
def mkSchemaType(schema: Schema): Result[Option[NamedType]] = {
def mkRootOperationType(rootTpe: RootOperationTypeDefinition): Result[(OperationType, Type)] = {
val RootOperationTypeDefinition(optype, tpe) = rootTpe
mkType(schema)(tpe).flatMap {
case NullableType(nt: NamedType) => (optype, nt).rightIor
case other => mkErrorResult(s"Root operation types must be named types, found $other (${other.productPrefix}).")
}
}
def build(query: Type, mutation: Option[Type], subscription: Option[Type]): NamedType = {
def mkRootDef(fieldName: String)(tpe: Type): Field =
Field(fieldName, None, Nil, tpe, false, None)
ObjectType(
name = "Schema",
description = None,
fields =
mkRootDef("query")(query) ::
List(
mutation.map(mkRootDef("mutation")),
subscription.map(mkRootDef("subscription"))
).flatten,
interfaces = Nil
)
}
def defaultQueryType = schema.ref("Query")
val defns = doc.collect { case schema: SchemaDefinition => schema }
defns match {
case Nil => None.rightIor
case SchemaDefinition(rootTpes, _) :: Nil =>
rootTpes.traverse(mkRootOperationType).map { ops0 =>
val ops = ops0.toMap
Some(build(ops.get(Query).getOrElse(defaultQueryType), ops.get(Mutation), ops.get(Subscription)))
}
case _ => mkErrorResult("At most one schema definition permitted")
}
}
def mkTypeDefs(schema: Schema): Result[List[NamedType]] = {
val defns: List[TypeDefinition] = doc.collect { case tpe: TypeDefinition => tpe }
val namedTypeResults = defns.traverse(mkTypeDef(schema))
SchemaValidator.validateSchema(namedTypeResults, defns)
}
def mkTypeDef(schema: Schema)(td: TypeDefinition): Result[NamedType] = td match {
case ScalarTypeDefinition(Name("Int"), _, _) => IntType.rightIor
case ScalarTypeDefinition(Name("Float"), _, _) => FloatType.rightIor
case ScalarTypeDefinition(Name("String"), _, _) => StringType.rightIor
case ScalarTypeDefinition(Name("Boolean"), _, _) => BooleanType.rightIor
case ScalarTypeDefinition(Name("ID"), _, _) => IDType.rightIor
case ScalarTypeDefinition(Name(nme), desc, _) => ScalarType(nme, desc).rightIor
case ObjectTypeDefinition(Name(nme), desc, fields0, ifs0, _) =>
if (fields0.isEmpty) mkErrorResult(s"object type $nme must define at least one field")
else
for {
fields <- fields0.traverse(mkField(schema))
ifs = ifs0.map { case Ast.Type.Named(Name(nme)) => schema.ref(nme) }
} yield ObjectType(nme, desc, fields, ifs)
case InterfaceTypeDefinition(Name(nme), desc, fields0, ifs0, _) =>
if (fields0.isEmpty) mkErrorResult(s"interface type $nme must define at least one field")
else
for {
fields <- fields0.traverse(mkField(schema))
ifs = ifs0.map { case Ast.Type.Named(Name(nme)) => schema.ref(nme) }
} yield InterfaceType(nme, desc, fields, ifs)
case UnionTypeDefinition(Name(nme), desc, _, members0) =>
if (members0.isEmpty) mkErrorResult(s"union type $nme must define at least one member")
else {
val members = members0.map { case Ast.Type.Named(Name(nme)) => schema.ref(nme) }
UnionType(nme, desc, members).rightIor
}
case EnumTypeDefinition(Name(nme), desc, _, values0) =>
if (values0.isEmpty) mkErrorResult(s"enum type $nme must define at least one enum value")
else
for {
values <- values0.traverse(mkEnumValue)
} yield EnumType(nme, desc, values)
case InputObjectTypeDefinition(Name(nme), desc, fields0, _) =>
if (fields0.isEmpty) mkErrorResult(s"input object type $nme must define at least one input field")
else
for {
fields <- fields0.traverse(mkInputValue(schema))
} yield InputObjectType(nme, desc, fields)
}
def mkField(schema: Schema)(f: FieldDefinition): Result[Field] = {
val FieldDefinition(Name(nme), desc, args0, tpe0, dirs) = f
for {
args <- args0.traverse(mkInputValue(schema))
tpe <- mkType(schema)(tpe0)
deprecation <- parseDeprecated(dirs)
(isDeprecated, reason) = deprecation
} yield Field(nme, desc, args, tpe, isDeprecated, reason)
}
def mkType(schema: Schema)(tpe: Ast.Type): Result[Type] = {
def loop(tpe: Ast.Type, nullable: Boolean): Result[Type] = {
def wrap(tpe: Type): Type = if (nullable) NullableType(tpe) else tpe
tpe match {
case Ast.Type.List(tpe) => loop(tpe, true).map(tpe => wrap(ListType(tpe)))
case Ast.Type.NonNull(Left(tpe)) => loop(tpe, false)
case Ast.Type.NonNull(Right(tpe)) => loop(tpe, false)
case Ast.Type.Named(Name(nme)) => wrap(ScalarType(nme).getOrElse(schema.ref(nme))).rightIor
}
}
loop(tpe, true)
}
def mkInputValue(schema: Schema)(f: InputValueDefinition): Result[InputValue] = {
val InputValueDefinition(Name(nme), desc, tpe0, default0, _) = f
for {
tpe <- mkType(schema)(tpe0)