forked from sangria-graphql/sangria
/
SchemaRenderer.scala
468 lines (392 loc) · 17.6 KB
/
SchemaRenderer.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
package sangria.renderer
import sangria.execution.ValueCoercionHelper
import sangria.introspection._
import sangria.marshalling.{InputUnmarshaller, ToInput}
import sangria.schema._
import sangria.ast
import sangria.ast.{AstNode, AstVisitor}
import sangria.introspection.__DirectiveLocation
import sangria.parser.QueryParser
import sangria.visitor.VisitorCommand
object SchemaRenderer {
def renderTypeName(tpe: Type, topLevel: Boolean = false) = {
def loop(t: Type, suffix: String): String = t match {
case OptionType(ofType) => loop(ofType, "")
case OptionInputType(ofType) => loop(ofType, "")
case ListType(ofType) => s"[${loop(ofType, "!")}]" + suffix
case ListInputType(ofType) => s"[${loop(ofType, "!")}]" + suffix
case named: Named => named.name + suffix
}
loop(tpe, if (topLevel) "" else "!")
}
def renderTypeNameAst(tpe: Type, topLevel: Boolean = false): ast.Type = {
def nn(tpe: ast.Type, notNull: Boolean) =
if (notNull) ast.NotNullType(tpe)
else tpe
def loop(t: Type, notNull: Boolean): ast.Type = t match {
case OptionType(ofType) => loop(ofType, false)
case OptionInputType(ofType) => loop(ofType, false)
case ListType(ofType) => nn(ast.ListType(loop(ofType, true)), notNull)
case ListInputType(ofType) => nn(ast.ListType(loop(ofType, true)), notNull)
case named: Named => nn(ast.NamedType(named.name), notNull)
}
loop(tpe, !topLevel)
}
def renderDescription(description: Option[String]): Option[ast.StringValue] =
description.flatMap { d =>
if (d.trim.nonEmpty) Some(ast.StringValue(d, block = d.indexOf('\n') > 0))
else None
}
def renderImplementedInterfaces(tpe: IntrospectionObjectType) =
tpe.interfaces.map(t => ast.NamedType(t.name)).toVector
def renderImplementedInterfaces(tpe: IntrospectionInterfaceType) =
tpe.interfaces.map(t => ast.NamedType(t.name)).toVector
def renderImplementedInterfaces(tpe: ObjectLikeType[_, _]) =
tpe.allInterfaces.map(t => ast.NamedType(t.name))
def renderTypeName(tpe: IntrospectionTypeRef): ast.Type =
tpe match {
case IntrospectionListTypeRef(ofType) => ast.ListType(renderTypeName(ofType))
case IntrospectionNonNullTypeRef(ofType) => ast.NotNullType(renderTypeName(ofType))
case IntrospectionNamedTypeRef(_, name) => ast.NamedType(name)
}
def renderDefault(defaultValue: Option[String]) =
defaultValue.flatMap(d => QueryParser.parseInput(d).toOption)
def renderDefault(value: (Any, ToInput[_, _]), tpe: InputType[_]) = {
val coercionHelper = new ValueCoercionHelper[Any]
DefaultValueRenderer.renderInputValue(value, tpe, coercionHelper)
}
def renderArg(arg: IntrospectionInputValue) =
ast.InputValueDefinition(
arg.name,
renderTypeName(arg.tpe),
renderDefault(arg.defaultValue),
description = renderDescription(arg.description))
def renderArg(arg: Argument[_]) =
ast.InputValueDefinition(
arg.name,
renderTypeNameAst(arg.argumentType),
arg.defaultValue.flatMap(renderDefault(_, arg.argumentType)),
arg.astDirectives,
renderDescription(arg.description)
)
def withoutDeprecated(dirs: Vector[ast.Directive]) = dirs.filterNot(_.name == "deprecated")
def renderDeprecation(isDeprecated: Boolean, reason: Option[String]) =
(isDeprecated, reason) match {
case (true, Some(r)) if r.trim == DefaultDeprecationReason =>
Vector(ast.Directive("deprecated", Vector.empty))
case (true, Some(r)) if r.trim.nonEmpty =>
Vector(ast.Directive("deprecated", Vector(ast.Argument("reason", ast.StringValue(r.trim)))))
case (true, _) => Vector(ast.Directive("deprecated", Vector.empty))
case _ => Vector.empty
}
def renderArgsI(args: Seq[IntrospectionInputValue]) =
args.map(renderArg).toVector
def renderArgs(args: Seq[Argument[_]]) =
args.map(renderArg).toVector
def renderFieldsI(fields: Seq[IntrospectionField]) =
fields.map(renderField).toVector
def renderFields(fields: Seq[Field[_, _]]) =
fields.map(renderField).toVector
def renderInputFieldsI(fields: Seq[IntrospectionInputValue]) =
fields.map(renderInputField).toVector
def renderInputFields(fields: Seq[InputField[_]]) =
fields.map(renderInputField).toVector
def renderField(field: IntrospectionField) =
ast.FieldDefinition(
field.name,
renderTypeName(field.tpe),
renderArgsI(field.args),
renderDeprecation(field.isDeprecated, field.deprecationReason),
renderDescription(field.description)
)
def renderField(field: Field[_, _]) =
ast.FieldDefinition(
field.name,
renderTypeNameAst(field.fieldType),
renderArgs(field.arguments),
withoutDeprecated(field.astDirectives) ++ renderDeprecation(
field.deprecationReason.isDefined,
field.deprecationReason),
renderDescription(field.description)
)
def renderInputField(field: IntrospectionInputValue) =
ast.InputValueDefinition(
field.name,
renderTypeName(field.tpe),
renderDefault(field.defaultValue),
description = renderDescription(field.description))
def renderInputField(field: InputField[_]) =
ast.InputValueDefinition(
field.name,
renderTypeNameAst(field.fieldType),
field.defaultValue.flatMap(renderDefault(_, field.fieldType)),
field.astDirectives,
renderDescription(field.description)
)
def renderObject(tpe: IntrospectionObjectType) =
ast.ObjectTypeDefinition(
tpe.name,
renderImplementedInterfaces(tpe),
renderFieldsI(tpe.fields),
description = renderDescription(tpe.description))
def renderObject(tpe: ObjectType[_, _]) =
ast.ObjectTypeDefinition(
tpe.name,
renderImplementedInterfaces(tpe),
renderFields(tpe.uniqueFields),
tpe.astDirectives,
renderDescription(tpe.description))
def renderEnum(tpe: IntrospectionEnumType) =
ast.EnumTypeDefinition(
tpe.name,
renderEnumValuesI(tpe.enumValues),
description = renderDescription(tpe.description))
def renderEnum(tpe: EnumType[_]) =
ast.EnumTypeDefinition(
tpe.name,
renderEnumValues(tpe.values),
tpe.astDirectives,
renderDescription(tpe.description))
def renderEnumValuesI(values: Seq[IntrospectionEnumValue]) =
values
.map(v =>
ast.EnumValueDefinition(
v.name,
renderDeprecation(v.isDeprecated, v.deprecationReason),
renderDescription(v.description)))
.toVector
def renderEnumValues(values: Seq[EnumValue[_]]) =
values.map(renderEnumValue).toVector
def renderEnumValue(v: EnumValue[_]) =
ast.EnumValueDefinition(
v.name,
withoutDeprecated(v.astDirectives) ++ renderDeprecation(
v.deprecationReason.isDefined,
v.deprecationReason),
renderDescription(v.description))
def renderScalar(tpe: IntrospectionScalarType) =
ast.ScalarTypeDefinition(tpe.name, description = renderDescription(tpe.description))
def renderScalar(tpe: ScalarType[_]) =
ast.ScalarTypeDefinition(tpe.name, tpe.astDirectives, renderDescription(tpe.description))
def renderInputObject(tpe: IntrospectionInputObjectType) =
ast.InputObjectTypeDefinition(
tpe.name,
renderInputFieldsI(tpe.inputFields),
description = renderDescription(tpe.description))
def renderInputObject(tpe: InputObjectType[_]) =
ast.InputObjectTypeDefinition(
tpe.name,
renderInputFields(tpe.fields),
tpe.astDirectives,
renderDescription(tpe.description))
def renderInterface(tpe: IntrospectionInterfaceType) =
ast.InterfaceTypeDefinition(
tpe.name,
renderImplementedInterfaces(tpe),
renderFieldsI(tpe.fields),
description = renderDescription(tpe.description))
def renderInterface(tpe: InterfaceType[_, _]) =
ast.InterfaceTypeDefinition(
tpe.name,
renderImplementedInterfaces(tpe),
renderFields(tpe.uniqueFields),
tpe.astDirectives,
renderDescription(tpe.description))
def renderUnion(tpe: IntrospectionUnionType) =
ast.UnionTypeDefinition(
tpe.name,
tpe.possibleTypes.map(t => ast.NamedType(t.name)).toVector,
description = renderDescription(tpe.description))
def renderUnion(tpe: UnionType[_]) =
ast.UnionTypeDefinition(
tpe.name,
tpe.types.map(t => ast.NamedType(t.name)).toVector,
tpe.astDirectives,
renderDescription(tpe.description))
private def renderSchemaDefinition(schema: IntrospectionSchema): Option[ast.SchemaDefinition] =
if (isSchemaOfCommonNames(
schema.queryType.name,
schema.mutationType.map(_.name),
schema.subscriptionType.map(_.name)))
None
else {
val withQuery = Vector(
ast.OperationTypeDefinition(ast.OperationType.Query, ast.NamedType(schema.queryType.name)))
val withMutation = schema.mutationType.fold(withQuery)(t =>
withQuery :+ ast.OperationTypeDefinition(ast.OperationType.Mutation, ast.NamedType(t.name)))
val withSubs = schema.subscriptionType.fold(withMutation)(t =>
withMutation :+ ast.OperationTypeDefinition(
ast.OperationType.Subscription,
ast.NamedType(t.name)))
Some(ast.SchemaDefinition(withSubs, description = renderDescription(schema.description)))
}
private def renderSchemaDefinition(schema: Schema[_, _]): Option[ast.SchemaDefinition] =
if (isSchemaOfCommonNames(
schema.query.name,
schema.mutation.map(_.name),
schema.subscription.map(
_.name)) && schema.description.isEmpty && schema.astDirectives.isEmpty)
None
else {
val withQuery = Vector(
ast.OperationTypeDefinition(ast.OperationType.Query, ast.NamedType(schema.query.name)))
val withMutation = schema.mutation.fold(withQuery)(t =>
withQuery :+ ast.OperationTypeDefinition(ast.OperationType.Mutation, ast.NamedType(t.name)))
val withSubs = schema.subscription.fold(withMutation)(t =>
withMutation :+ ast.OperationTypeDefinition(
ast.OperationType.Subscription,
ast.NamedType(t.name)))
Some(
ast.SchemaDefinition(withSubs, schema.astDirectives, renderDescription(schema.description)))
}
private def isSchemaOfCommonNames(
query: String,
mutation: Option[String],
subscription: Option[String]) =
query == "Query" && mutation.fold(true)(_ == "Mutation") && subscription.fold(true)(
_ == "Subscription")
def renderType(tpe: IntrospectionType): ast.TypeDefinition =
tpe match {
case o: IntrospectionObjectType => renderObject(o)
case u: IntrospectionUnionType => renderUnion(u)
case i: IntrospectionInterfaceType => renderInterface(i)
case io: IntrospectionInputObjectType => renderInputObject(io)
case s: IntrospectionScalarType => renderScalar(s)
case e: IntrospectionEnumType => renderEnum(e)
case kind => throw new IllegalArgumentException(s"Unsupported kind: $kind")
}
def renderType(tpe: Type with Named): ast.TypeDefinition =
tpe match {
case o: ObjectType[_, _] => renderObject(o)
case u: UnionType[_] => renderUnion(u)
case i: InterfaceType[_, _] => renderInterface(i)
case io: InputObjectType[_] => renderInputObject(io)
case s: ScalarType[_] => renderScalar(s)
case s: ScalarAlias[_, _] => renderScalar(s.aliasFor)
case e: EnumType[_] => renderEnum(e)
case _ => throw new IllegalArgumentException(s"Unsupported type: $tpe")
}
def renderDirectiveLocation(loc: DirectiveLocation.Value) =
ast.DirectiveLocation(__DirectiveLocation.byValue(loc).name)
def renderDirective(dir: Directive) =
ast.DirectiveDefinition(
dir.name,
renderArgs(dir.arguments),
dir.locations.toVector.map(renderDirectiveLocation).sortBy(_.name),
renderDescription(dir.description))
def renderDirective(dir: IntrospectionDirective) =
ast.DirectiveDefinition(
dir.name,
renderArgsI(dir.args),
dir.locations.toVector.map(renderDirectiveLocation).sortBy(_.name),
renderDescription(dir.description))
def schemaAstFromIntrospection(
introspectionSchema: IntrospectionSchema,
filter: SchemaFilter = SchemaFilter.default): ast.Document = {
val schemaDef = if (filter.renderSchema) renderSchemaDefinition(introspectionSchema) else None
val types = introspectionSchema.types
.filter(t => filter.filterTypes(t.name))
.sortBy(_.name)
.map(renderType)
val directives = introspectionSchema.directives
.filter(d => filter.filterDirectives(d.name))
.sortBy(_.name)
.map(renderDirective)
ast.Document(schemaDef.toVector ++ types ++ directives)
}
def renderSchema(introspectionSchema: IntrospectionSchema): String =
schemaAstFromIntrospection(introspectionSchema, SchemaFilter.default).renderPretty
def renderSchema[T: InputUnmarshaller](introspectionResult: T): String = {
import sangria.parser.DeliveryScheme.Throw
schemaAstFromIntrospection(
IntrospectionParser.parse(introspectionResult),
SchemaFilter.default).renderPretty
}
def renderSchema(introspectionSchema: IntrospectionSchema, filter: SchemaFilter): String =
schemaAstFromIntrospection(introspectionSchema, filter).renderPretty
def renderSchema[T: InputUnmarshaller](introspectionResult: T, filter: SchemaFilter): String = {
import sangria.parser.DeliveryScheme.Throw
schemaAstFromIntrospection(IntrospectionParser.parse(introspectionResult), filter).renderPretty
}
def schemaAst(schema: Schema[_, _], filter: SchemaFilter = SchemaFilter.default): ast.Document = {
val schemaDef = if (filter.renderSchema) renderSchemaDefinition(schema) else None
val types =
schema.typeList.filter(t => filter.filterTypes(t.name)).sortBy(_.name).map(renderType)
val directives = schema.directives
.filter(d => filter.filterDirectives(d.name))
.sortBy(_.name)
.map(renderDirective)
val document = ast.Document(schemaDef.toVector ++ types ++ directives)
if (filter.legacyCommentDescriptions) transformLegacyCommentDescriptions(document)
else document
}
def transformLegacyCommentDescriptions[T <: AstNode](node: T): T =
AstVisitor.visit(
node,
AstVisitor {
case n: ast.DirectiveDefinition if n.description.isDefined =>
VisitorCommand.Transform(
n.copy(description = None, comments = n.comments ++ commentDescription(n)))
case n: ast.InterfaceTypeDefinition if n.description.isDefined =>
VisitorCommand.Transform(
n.copy(description = None, comments = n.comments ++ commentDescription(n)))
case n: ast.EnumTypeDefinition if n.description.isDefined =>
VisitorCommand.Transform(
n.copy(description = None, comments = n.comments ++ commentDescription(n)))
case n: ast.EnumValueDefinition if n.description.isDefined =>
VisitorCommand.Transform(
n.copy(description = None, comments = n.comments ++ commentDescription(n)))
case n: ast.FieldDefinition if n.description.isDefined =>
VisitorCommand.Transform(
n.copy(description = None, comments = n.comments ++ commentDescription(n)))
case n: ast.InputObjectTypeDefinition if n.description.isDefined =>
VisitorCommand.Transform(
n.copy(description = None, comments = n.comments ++ commentDescription(n)))
case n: ast.InputValueDefinition if n.description.isDefined =>
VisitorCommand.Transform(
n.copy(description = None, comments = n.comments ++ commentDescription(n)))
case n: ast.ObjectTypeDefinition if n.description.isDefined =>
VisitorCommand.Transform(
n.copy(description = None, comments = n.comments ++ commentDescription(n)))
case n: ast.ScalarTypeDefinition if n.description.isDefined =>
VisitorCommand.Transform(
n.copy(description = None, comments = n.comments ++ commentDescription(n)))
case n: ast.UnionTypeDefinition if n.description.isDefined =>
VisitorCommand.Transform(
n.copy(description = None, comments = n.comments ++ commentDescription(n)))
}
)
private def commentDescription(node: ast.WithDescription) =
node.description.toVector.flatMap(sv => sv.value.split("\\r?\\n").toVector.map(ast.Comment(_)))
def renderSchema(schema: Schema[_, _]): String =
schemaAst(schema, SchemaFilter.default).renderPretty
def renderSchema(schema: Schema[_, _], filter: SchemaFilter): String =
schemaAst(schema, filter).renderPretty
}
case class SchemaFilter(
filterTypes: String => Boolean,
filterDirectives: String => Boolean,
renderSchema: Boolean = true,
legacyCommentDescriptions: Boolean = false) {
@deprecated("Please migrate to new string-based description format", "1.4.0")
def withLegacyCommentDescriptions = copy(legacyCommentDescriptions = true)
}
object SchemaFilter {
val withoutSangriaBuiltIn: SchemaFilter = SchemaFilter(
typeName => !Schema.isBuiltInType(typeName),
dirName => !Schema.isBuiltInDirective(dirName))
val default: SchemaFilter = withoutSangriaBuiltIn
val withoutGraphQLBuiltIn = SchemaFilter(
typeName => !Schema.isBuiltInGraphQLType(typeName),
dirName => !Schema.isBuiltInDirective(dirName))
val withoutIntrospection: SchemaFilter =
SchemaFilter(typeName => !Schema.isIntrospectionType(typeName), Function.const(true))
val builtIn: SchemaFilter = SchemaFilter(
typeName => Schema.isBuiltInType(typeName),
dirName => Schema.isBuiltInDirective(dirName))
val introspection: SchemaFilter = SchemaFilter(
typeName => Schema.isIntrospectionType(typeName),
Function.const(false),
renderSchema = false)
val all: SchemaFilter = SchemaFilter(Function.const(true), Function.const(true))
}