-
Notifications
You must be signed in to change notification settings - Fork 27
/
schema.scala
2064 lines (1807 loc) · 74.3 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-2023 Association of Universities for Research in Astronomy, Inc. (AURA)
// Copyright (c) 2016-2023 Grackle Contributors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package grackle
import cats.implicits._
import io.circe.Json
import org.tpolecat.sourcepos.SourcePos
import syntax._
import Ast.{DirectiveLocation, InterfaceTypeDefinition, ObjectTypeDefinition, TypeDefinition, UnionTypeDefinition}
import Query._
import ScalarType._
import UntypedOperation._
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` prior to any extensions. */
def baseTypes: List[NamedType]
/** The types defined by this `Schema` with any extensions applied. */
lazy val types: List[NamedType] =
if (typeExtensions.isEmpty) baseTypes
else baseTypes.map(extendType(typeExtensions))
/** The directives defined by this `Schema`. */
def directives: List[DirectiveDef]
/** The schema extensions defined by this `Schema` */
def schemaExtensions: List[SchemaExtension]
/** The type extensions defined by this `Schema` */
def typeExtensions: List[TypeExtension]
/** 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, Nil)
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,
directives = 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.builtIn(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
}
def baseSchemaType: NamedType = definition("Schema").getOrElse(defaultSchemaType)
/**
* The schema type.
*
* Either the explicitly defined type named `"Schema"` or the default
* schema type if not defined.
*/
lazy val schemaType: NamedType =
if (schemaExtensions.isEmpty) baseSchemaType
else extendSchemaType(schemaExtensions, baseSchemaType)
/** The type of queries defined by this `Schema`*/
def queryType: NamedType = schemaType.field("query").flatMap(_.nonNull.asNamed).get
/** The type of mutations defined by this `Schema`*/
def mutationType: Option[NamedType] = schemaType.field("mutation").flatMap(_.nonNull.asNamed)
/** The type of subscriptions defined by this `Schema`*/
def subscriptionType: Option[NamedType] = schemaType.field("subscription").flatMap(_.nonNull.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.exists(_ =:= tpe) || subscriptionType.exists(_ =:= tpe)
/** 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)
private def extendType(extns: List[TypeExtension])(baseType: NamedType): NamedType = {
baseType match {
case ScalarType(name, description, directives) =>
val exts = extns.collect { case se@ScalarExtension(`name`, _) => se }
if (exts.isEmpty) baseType
else {
val newDirectives = exts.flatMap(_.directives)
ScalarType(name, description, directives ++ newDirectives)
}
case InterfaceType(name, description, fields, interfaces, directives) =>
val exts = extns.collect { case ie@InterfaceExtension(`name`, _, _, _) => ie }
if (exts.isEmpty) baseType
else {
val newFields = exts.flatMap(_.fields)
val newInterfaces = exts.flatMap(_.interfaces)
val newDirectives = exts.flatMap(_.directives)
InterfaceType(name, description, fields ++ newFields, interfaces ++ newInterfaces, directives ++ newDirectives)
}
case ObjectType(name, description, fields, interfaces, directives) =>
val exts = extns.collect { case oe@ObjectExtension(`name`, _, _, _) => oe }
if (exts.isEmpty) baseType
else {
val newFields = exts.flatMap(_.fields)
val newInterfaces = exts.flatMap(_.interfaces)
val newDirectives = exts.flatMap(_.directives)
ObjectType(name, description, fields ++ newFields, interfaces ++ newInterfaces, directives ++ newDirectives)
}
case UnionType(name, description, members, directives) =>
val exts = extns.collect { case ue@UnionExtension(`name`, _, _) => ue }
if (exts.isEmpty) baseType
else {
val newMembers = exts.flatMap(_.members)
val newDirectives = exts.flatMap(_.directives)
UnionType(name, description, members ++ newMembers, directives ++ newDirectives)
}
case EnumType(name, description, enumValues, directives) =>
val exts = extns.collect { case ee@EnumExtension(`name`, _, _) => ee }
if (exts.isEmpty) baseType
else {
val newValues = exts.flatMap(_.enumValues)
val newDirectives = exts.flatMap(_.directives)
EnumType(name, description, enumValues ++ newValues, directives ++ newDirectives)
}
case InputObjectType(name, description, inputFields, directives) =>
val exts = extns.collect { case ioe@InputObjectExtension(`name`, _, _) => ioe }
if (exts.isEmpty) baseType
else {
val newFields = exts.flatMap(_.inputFields)
val newDirectives = exts.flatMap(_.directives)
InputObjectType(name, description, inputFields ++ newFields, directives ++ newDirectives)
}
case tr: TypeRef =>
// This case should never be hit, however, it is the correct behaviour to return
// the ref as is. If the underlying type is present it will be extended, if not
// there will be an error reported elsewhere.
tr
}
}
private def extendSchemaType(extns: List[SchemaExtension], schemaType: NamedType): NamedType = {
schemaType match {
case ObjectType(name, description, fields, interfaces, directives) =>
val newFields = extns.flatMap(_.rootOperations)
val newDirectives = extns.flatMap(_.directives)
ObjectType(name, description, fields ++ newFields, interfaces, directives ++ newDirectives)
case _ => schemaType
}
}
}
object Schema {
def apply(schemaText: String)(implicit pos: SourcePos): Result[Schema] =
apply(schemaText, SchemaParser(GraphQLParser(GraphQLParser.defaultConfig)))
def apply(schemaText: String, parser: SchemaParser)(implicit pos: SourcePos): Result[Schema] =
parser.parseText(schemaText)
}
case class SchemaExtension(
rootOperations: List[Field],
directives: List[Directive]
)
/**
* 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 <:< _)
case (ObjectType(_, _, _, interfaces, _), tp2) => interfaces.exists(_ <:< tp2)
case (InterfaceType(_, _, _, interfaces, _), tp2) => interfaces.exists(_ <:< tp2)
case (NullableType(tp1), NullableType(tp2)) => tp1 <:< tp2
case (tp1, NullableType(tp2)) => tp1 <:< tp2
case (ListType(tp1), ListType(tp2)) => tp1 <:< 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
/** Yields the definition of `fieldName` in this type if it exists, `None` otherwise. */
def fieldInfo(fieldName: String): Option[Field] = this match {
case NullableType(tpe) => tpe.fieldInfo(fieldName)
case ListType(tpe) => tpe.fieldInfo(fieldName)
case _: TypeRef => dealias.fieldInfo(fieldName)
case _ => None
}
/**
* `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
}
/**
* 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).exists(_.tpe.pathIsList(rest))
case (fieldName :: rest, InterfaceType(_, _, fields, _, _)) =>
fields.find(_.name == fieldName).exists(_.tpe.pathIsList(rest))
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).exists(_.tpe.pathIsNullable(rest))
case (fieldName :: rest, InterfaceType(_, _, fields, _, _)) =>
fields.find(_.name == fieldName).exists(_.tpe.pathIsNullable(rest))
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[NamedType] = 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
}
/**
* Yield the named type underlying this type.
*
* Strips of nullability and enclosing list types until an
* underlying named type is reached. This method will always
* yield a named type.
*/
def underlyingNamed: NamedType = this match {
case NullableType(tpe) => tpe.underlyingNamed
case ListType(tpe) => tpe.underlyingNamed
case tpe: NamedType => tpe
}
/** 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
def directives: List[Directive]
}
// 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]
def directives: List[Directive]
override def toString: String = name
}
/**
* A GraphQL type extension
*/
sealed trait TypeExtension {
def baseType: String
}
/**
* 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
def directives: List[Directive] = dealias.directives
}
/**
* 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],
directives: List[Directive]
) 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 builtIn(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
),
directives = Nil
)
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
),
directives = Nil
)
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
),
directives = Nil
)
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
),
directives = Nil
)
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
),
directives = Nil
)
val AttributeType = ScalarType(
name = "InternalAttribute",
description = None,
directives = Nil
)
}
/**
* A type with fields.
*
* This includes object types and inferface types.
*/
sealed trait TypeWithFields extends NamedType {
def fields: List[Field]
def interfaces: List[NamedType]
override def fieldInfo(name: String): Option[Field] = fields.find(_.name == name)
}
/**
* Scalar extensions allow additional directives to be applied to a pre-existing Scalar type
*
* @see https://spec.graphql.org/draft/#sec-Scalar-Extensions
*/
case class ScalarExtension(
baseType: String,
directives: List[Directive]
) extends TypeExtension
/**
* 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],
directives: List[Directive]
) extends TypeWithFields {
override def isInterface: Boolean = true
}
/**
* Interface extensions allow additional fields to be added to a pre-existing interface type
*
* @see https://spec.graphql.org/draft/#sec-Interface-Extensions
**/
case class InterfaceExtension(
baseType: String,
fields: List[Field],
interfaces: List[NamedType],
directives: List[Directive]
) extends TypeExtension
/**
* 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],
directives: List[Directive]
) extends TypeWithFields
/**
* Object extensions allow additional fields to be added to a pre-existing object type
*
* @see https://spec.graphql.org/draft/#sec-Object-Extensions
**/
case class ObjectExtension(
baseType: String,
fields: List[Field],
interfaces: List[NamedType],
directives: List[Directive]
) extends TypeExtension
/**
* 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],
directives: List[Directive]
) extends Type with NamedType {
override def isUnion: Boolean = true
override def toString: String = members.mkString("|")
}
/**
* Union extensions allow additional members to be added to a pre-existing union type
*
* @see https://spec.graphql.org/draft/#sec-Union-Extensions
**/
case class UnionExtension(
baseType: String,
members: List[NamedType],
directives: List[Directive]
) extends TypeExtension
/**
* 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[EnumValueDefinition],
directives: List[Directive]
) extends Type with NamedType {
def hasValue(name: String): Boolean = enumValues.exists(_.name == name)
def value(name: String): Option[EnumValue] = valueDefinition(name).map(_ => EnumValue(name))
def valueDefinition(name: String): Option[EnumValueDefinition] = enumValues.find(_.name == name)
}
/**
* Enum extensions allow additional values to be added to a pre-existing enum type
*
* @see https://spec.graphql.org/draft/#sec-Enum-Extensions
**/
case class EnumExtension(
baseType: String,
enumValues: List[EnumValueDefinition],
directives: List[Directive]
) extends TypeExtension
/**
* The `EnumValue` type represents one of possible values of an enum.
*
* @see https://facebook.github.io/graphql/draft/#sec-The-__EnumValue-Type
*/
case class EnumValueDefinition(
name: String,
description: Option[String],
directives: List[Directive]
) {
def deprecatedDirective: Option[Directive] =
directives.find(_.name == "deprecated")
def isDeprecated: Boolean = deprecatedDirective.isDefined
def deprecationReason: Option[String] =
for {
dir <- deprecatedDirective
reason <- dir.args.collectFirst { case Binding("reason", StringValue(reason)) => reason }
} yield reason
}
/**
* 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],
directives: List[Directive]
) extends Type with NamedType {
def inputFieldInfo(name: String): Option[InputValue] = inputFields.find(_.name == name)
}
/**
* Input Object extensions allow additional fields to be added to a pre-existing Input Object type
*
* @see https://spec.graphql.org/draft/#sec-Input-Object-Extensions
**/
case class InputObjectExtension(
baseType: String,
inputFields: List[InputValue],
directives: List[Directive]
) extends TypeExtension
/**
* 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 {
def directives: List[Directive] = Nil
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 {
def directives: List[Directive] = Nil
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,
directives: List[Directive]
) {
def deprecatedDirective: Option[Directive] =
directives.find(_.name == "deprecated")
def isDeprecated: Boolean = deprecatedDirective.isDefined
def deprecationReason: Option[String] =
for {
dir <- deprecatedDirective
reason <- dir.args.collectFirst { case Binding("reason", StringValue(reason)) => reason }
} yield reason
}
/**
* @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],
directives: List[Directive]
)
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 EnumValue(name: String) extends Value
case class ListValue(elems: List[Value]) extends Value
case class ObjectValue(fields: List[(String, Value)]) extends Value
case class VariableRef(name: String) extends Value
case object NullValue extends Value
case object AbsentValue extends Value
def fromAst(value: Ast.Value): Result[Value] = {
value match {
case Ast.Value.IntValue(i) => IntValue(i).success
case Ast.Value.FloatValue(d) => FloatValue(d).success
case Ast.Value.StringValue(s) => StringValue(s).success
case Ast.Value.BooleanValue(b) => BooleanValue(b).success
case Ast.Value.EnumValue(e) => EnumValue(e.value).success
case Ast.Value.Variable(v) => VariableRef(v.value).success
case Ast.Value.NullValue => NullValue.success
case Ast.Value.ListValue(vs) => vs.traverse(fromAst).map(ListValue(_))
case Ast.Value.ObjectValue(fs) =>
fs.traverse { case (name, value) =>
fromAst(value).map(v => (name.value, v))
}.map(ObjectValue(_))
}
}
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
}
}
/**
* Elaborate a value by replacing variable references with their values.
*/
def elaborateValue(value: Value, vars: Vars): Result[Value] = {
def loop(value: Value): Result[Value] =
value match {
case VariableRef(varName) =>
Result.fromOption(vars.get(varName).map(_._2), s"Variable '$varName' is undefined")
case ObjectValue(fields) =>
val (keys, values) = fields.unzip
values.traverse(loop).map(evs => ObjectValue(keys.zip(evs)))