forked from nautilus/graphql
-
Notifications
You must be signed in to change notification settings - Fork 0
/
introspection.go
577 lines (497 loc) · 16.4 KB
/
introspection.go
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
package graphql
import (
"context"
"errors"
"fmt"
"net/http"
"github.com/vektah/gqlparser/v2/ast"
)
// IntrospectOptions represents the options for the IntrospectAPI function
type IntrospectOptions struct {
wares []NetworkMiddleware
client *http.Client
ctx context.Context
}
// Context returns either a given context or an instance of the context.Background
func (o *IntrospectOptions) Context() context.Context {
if o.ctx == nil {
return context.Background()
}
return o.ctx
}
// Apply applies the options to a given queryer
func (o *IntrospectOptions) Apply(queryer Queryer) Queryer {
if q, ok := queryer.(QueryerWithMiddlewares); ok && len(o.wares) > 0 {
queryer = q.WithMiddlewares(o.wares)
}
if q, ok := queryer.(HTTPQueryer); ok && o.client != nil {
queryer = q.WithHTTPClient(o.client)
}
return queryer
}
func mergeIntrospectOptions(opts ...*IntrospectOptions) *IntrospectOptions {
res := &IntrospectOptions{}
for _, opt := range opts {
if len(opt.wares) > 0 {
res.wares = append(res.wares, opt.wares...)
}
if opt.client != nil {
res.client = opt.client
}
if opt.ctx != nil {
res.ctx = opt.ctx
}
}
return res
}
// IntrospectWithMiddlewares returns an instance of graphql.IntrospectOptions with given middlewares
// to be pass to an instance of a graphql.Queryer by the IntrospectOptions.Apply function
func IntrospectWithMiddlewares(wares ...NetworkMiddleware) *IntrospectOptions {
return &IntrospectOptions{
wares: wares,
}
}
// IntrospectWithHTTPClient returns an instance of graphql.IntrospectOptions with given client
// to be pass to an instance of a graphql.Queryer by the IntrospectOptions.Apply function
func IntrospectWithHTTPClient(client *http.Client) *IntrospectOptions {
return &IntrospectOptions{
client: client,
}
}
// IntrospectWithHTTPClient returns an instance of graphql.IntrospectOptions with given context
// to be used as a parameter for graphql.Queryer.Query function in the graphql.IntrospectAPI function
func IntrospectWithContext(ctx context.Context) *IntrospectOptions {
return &IntrospectOptions{
ctx: ctx,
}
}
// IntrospectRemoteSchema is used to build a RemoteSchema by firing the introspection query
// at a remote service and reconstructing the schema object from the response
func IntrospectRemoteSchema(url string, opts ...*IntrospectOptions) (*RemoteSchema, error) {
// introspect the schema at the designated url
schema, err := IntrospectAPI(NewSingleRequestQueryer(url), opts...)
if err != nil {
return nil, err
}
return &RemoteSchema{
URL: url,
Schema: schema,
}, nil
}
// IntrospectRemoteSchemas takes a list of URLs and creates a RemoteSchema by invoking
// graphql.IntrospectRemoteSchema at that location.
func IntrospectRemoteSchemas(urls ...string) ([]*RemoteSchema, error) {
return IntrospectRemoteSchemasWithOptions(urls)
}
// IntrospectRemoteSchemasWithOptions takes a list of URLs and an optional list of graphql.IntrospectionOptions
// and creates a RemoteSchema by invoking graphql.IntrospectRemoteSchema at that location.
func IntrospectRemoteSchemasWithOptions(urls []string, opts ...*IntrospectOptions) ([]*RemoteSchema, error) {
// build up the list of remote schemas
schemas := []*RemoteSchema{}
for _, service := range urls {
// introspect the locations
schema, err := IntrospectRemoteSchema(service, opts...)
if err != nil {
return nil, err
}
// add the schema to the list
schemas = append(schemas, schema)
}
return schemas, nil
}
// IntrospectAPI send the introspection query to a Queryer and builds up the
// schema object described by the result
func IntrospectAPI(queryer Queryer, opts ...*IntrospectOptions) (*ast.Schema, error) {
// apply the options to the given queryer
opt := mergeIntrospectOptions(opts...)
queryer = opt.Apply(queryer)
// a place to hold the result of firing the introspection query
result := IntrospectionQueryResult{}
input := &QueryInput{
Query: IntrospectionQuery,
OperationName: "IntrospectionQuery",
}
// fire the introspection query
err := queryer.Query(opt.Context(), input, &result)
if err != nil {
return nil, err
}
// grab the schema
remoteSchema := result.Schema
// create a schema we will build up over time
schema := &ast.Schema{
Types: map[string]*ast.Definition{},
Directives: map[string]*ast.DirectiveDefinition{},
PossibleTypes: map[string][]*ast.Definition{},
Implements: map[string][]*ast.Definition{},
}
// if we dont have a name on the response
if remoteSchema == nil || remoteSchema.QueryType.Name == "" {
return nil, errors.New("Could not find the root query")
}
// reconstructing the schema happens in a few pass throughs
// the first builds a map of type names to their definition
// the second pass goes over the definitions and reconstructs the types
// add each type to the schema
for _, remoteType := range remoteSchema.Types {
// convert turn the API payload into a schema type
schemaType := introspectionUnmarshalType(remoteType)
// check if this type is the QueryType
if remoteType.Name == remoteSchema.QueryType.Name {
schema.Query = schemaType
} else if remoteSchema.MutationType != nil && schemaType.Name == remoteSchema.MutationType.Name {
schema.Mutation = schemaType
} else if remoteSchema.SubscriptionType != nil && schemaType.Name == remoteSchema.SubscriptionType.Name {
schema.Subscription = schemaType
}
// register the type with the schema
schema.Types[schemaType.Name] = schemaType
}
// the second pass constructs the fields and
for _, remoteType := range remoteSchema.Types {
// a reference to the type
storedType, ok := schema.Types[remoteType.Name]
if !ok {
return nil, err
}
// make sure we record that a type implements itself
schema.AddImplements(remoteType.Name, storedType)
// if we are looking at an enum
if len(remoteType.PossibleTypes) > 0 {
// build up an empty list of types
storedType.Types = []string{}
// each union value needs to be added to the list
for _, possibleType := range remoteType.PossibleTypes {
// if there is no name
if possibleType.Name == "" {
return nil, errors.New("Could not find name of type")
}
// add the type to the union definition
if remoteType.Name != storedType.Name {
storedType.Types = append(storedType.Types, possibleType.Name)
}
possibleTypeDef, ok := schema.Types[possibleType.Name]
if !ok {
return nil, errors.New("Could not find type definition for union implementation")
}
// add the possible type to the schema
schema.AddPossibleType(remoteType.Name, possibleTypeDef)
schema.AddImplements(possibleType.Name, storedType)
}
}
if len(remoteType.Interfaces) > 0 {
// each interface value needs to be added to the list
for _, iFace := range remoteType.Interfaces {
// if there is no name
if iFace.Name == "" {
return nil, errors.New("Could not find name of type")
}
// add the type to the union definition
storedType.Interfaces = append(storedType.Interfaces, iFace.Name)
iFaceDef, ok := schema.Types[iFace.Name]
if !ok {
return nil, errors.New("Could not find type definition for union implementation")
}
// add the possible type to the schema
schema.AddPossibleType(iFaceDef.Name, storedType)
schema.AddImplements(storedType.Name, iFaceDef)
}
}
// build up a list of fields associated with the type
fields := ast.FieldList{}
for _, field := range remoteType.Fields {
// add the field to the list
fields = append(fields, &ast.FieldDefinition{
Name: field.Name,
Type: introspectionUnmarshalTypeRef(&field.Type),
Description: field.Description,
Arguments: introspectionConvertArgList(field.Args),
})
}
for _, field := range remoteType.InputFields {
// add the field to the list
fields = append(fields, &ast.FieldDefinition{
Name: field.Name,
Type: introspectionUnmarshalTypeRef(&field.Type),
Description: field.Description,
})
}
// save the list of fields in the schema type
storedType.Fields = fields
}
// add each directive to the schema
for _, directive := range remoteSchema.Directives {
// if we dont have a name
if directive.Name == "" {
return nil, errors.New("could not find directive name")
}
// the list of directive locations
locations, err := introspectionUnmarshalDirectiveLocation(directive.Locations)
if err != nil {
return nil, err
}
// save the directive definition to the schema
schema.Directives[directive.Name] = &ast.DirectiveDefinition{
Position: &ast.Position{Src: &ast.Source{}},
Name: directive.Name,
Description: directive.Description,
Arguments: introspectionConvertArgList(directive.Args),
Locations: locations,
}
switch directive.Name {
case "skip", "deprecated", "include":
schema.Directives[directive.Name].Position.Src.BuiltIn = true
}
}
// we're done here
return schema, nil
}
func introspectionConvertArgList(args []IntrospectionInputValue) ast.ArgumentDefinitionList {
result := ast.ArgumentDefinitionList{}
// we need to add each argument to the field
for _, argument := range args {
result = append(result, &ast.ArgumentDefinition{
Name: argument.Name,
Description: argument.Description,
Type: introspectionUnmarshalTypeRef(&argument.Type),
})
}
return result
}
func introspectionUnmarshalType(schemaType IntrospectionQueryFullType) *ast.Definition {
definition := &ast.Definition{
Name: schemaType.Name,
Description: schemaType.Description,
}
// the kind of type
switch schemaType.Kind {
case "OBJECT":
definition.Kind = ast.Object
case "SCALAR":
definition.Kind = ast.Scalar
case "INTERFACE":
definition.Kind = ast.Interface
case "UNION":
definition.Kind = ast.Union
case "INPUT_OBJECT":
definition.Kind = ast.InputObject
case "ENUM":
definition.Kind = ast.Enum
// save the enum values
definition.EnumValues = ast.EnumValueList{}
// convert each enum value into the appropriate object
for _, value := range schemaType.EnumValues {
definition.EnumValues = append(definition.EnumValues, &ast.EnumValueDefinition{
Name: value.Name,
Description: value.Description,
})
}
}
switch schemaType.Name {
case "ID", "Int", "Float", "String", "Boolean",
"__Schema", "__Type", "__InputValue", "__TypeKind",
"__DirectiveLocation", "__Field", "__EnumValue", "__Directive":
definition.BuiltIn = true
}
return definition
}
// a mapping of marshaled directive locations to their parsed equivalent
var directiveLocationMap map[string]ast.DirectiveLocation
func introspectionUnmarshalDirectiveLocation(locs []string) ([]ast.DirectiveLocation, error) {
result := []ast.DirectiveLocation{}
// each location needs to be mapped over
for _, value := range locs {
// look up the directive location for the API response
location, ok := directiveLocationMap[value]
if !ok {
return nil, fmt.Errorf("encountered unknown directive location: %s", value)
}
// add the result to the list
result = append(result, location)
}
// we're done
return result, nil
}
func introspectionUnmarshalTypeRef(response *IntrospectionTypeRef) *ast.Type {
// we could have a non-null list of a field
if response.Kind == "NON_NULL" && response.OfType.Kind == "LIST" {
return ast.NonNullListType(introspectionUnmarshalTypeRef(response.OfType.OfType), &ast.Position{})
}
// we could have a list of a type
if response.Kind == "LIST" {
return ast.ListType(introspectionUnmarshalTypeRef(response.OfType), &ast.Position{})
}
// we could have just a non null
if response.Kind == "NON_NULL" {
return ast.NonNullNamedType(response.OfType.Name, &ast.Position{})
}
// if we are looking at a named type that isn't in a list or marked non-null
return ast.NamedType(response.Name, &ast.Position{})
}
func init() {
directiveLocationMap = map[string]ast.DirectiveLocation{
"QUERY": ast.LocationQuery,
"MUTATION": ast.LocationMutation,
"SUBSCRIPTION": ast.LocationSubscription,
"FIELD": ast.LocationField,
"FRAGMENT_DEFINITION": ast.LocationFragmentDefinition,
"FRAGMENT_SPREAD": ast.LocationFragmentSpread,
"INLINE_FRAGMENT": ast.LocationInlineFragment,
"SCHEMA": ast.LocationSchema,
"SCALAR": ast.LocationScalar,
"OBJECT": ast.LocationObject,
"FIELD_DEFINITION": ast.LocationFieldDefinition,
"ARGUMENT_DEFINITION": ast.LocationArgumentDefinition,
"INTERFACE": ast.LocationInterface,
"UNION": ast.LocationUnion,
"ENUM": ast.LocationEnum,
"ENUM_VALUE": ast.LocationEnumValue,
"INPUT_OBJECT": ast.LocationInputObject,
"INPUT_FIELD_DEFINITION": ast.LocationInputFieldDefinition,
}
}
type IntrospectionQueryResult struct {
Schema *IntrospectionQuerySchema `json:"__schema"`
}
type IntrospectionQuerySchema struct {
QueryType IntrospectionQueryRootType `json:"queryType"`
MutationType *IntrospectionQueryRootType `json:"mutationType"`
SubscriptionType *IntrospectionQueryRootType `json:"subscriptionType"`
Types []IntrospectionQueryFullType `json:"types"`
Directives []IntrospectionQueryDirective `json:"directives"`
}
type IntrospectionQueryDirective struct {
Name string `json:"name"`
Description string `json:"description"`
Locations []string `json:"locations"`
Args []IntrospectionInputValue `json:"args"`
}
type IntrospectionQueryRootType struct {
Name string `json:"name"`
}
type IntrospectionQueryFullTypeField struct {
Name string `json:"name"`
Description string `json:"description"`
Args []IntrospectionInputValue `json:"args"`
Type IntrospectionTypeRef `json:"type"`
IsDeprecated bool `json:"isDeprecated"`
DeprecationReason string `json:"deprecationReason"`
}
type IntrospectionQueryFullType struct {
Kind string `json:"kind"`
Name string `json:"name"`
Description string `json:"description"`
InputFields []IntrospectionInputValue `json:"inputFields"`
Interfaces []IntrospectionTypeRef `json:"interfaces"`
PossibleTypes []IntrospectionTypeRef `json:"possibleTypes"`
Fields []IntrospectionQueryFullTypeField `json:"fields"`
EnumValues []IntrospectionQueryEnumDefinition `json:"enumValues"`
}
type IntrospectionQueryEnumDefinition struct {
Name string `json:"name"`
Description string `json:"description"`
IsDeprecated bool `json:"isDeprecated"`
DeprecationReason string `json:"deprecationReason"`
}
type IntrospectionInputValue struct {
Name string `json:"name"`
Description string `json:"description"`
DefaultValue string `json:"defaultValue"`
Type IntrospectionTypeRef `json:"type"`
}
type IntrospectionTypeRef struct {
Kind string `json:"kind"`
Name string `json:"name"`
OfType *IntrospectionTypeRef `json:"ofType"`
}
// IntrospectionQuery is the query that is fired at an API to reconstruct its schema
var IntrospectionQuery = `
query IntrospectionQuery {
__schema {
queryType { name }
mutationType { name }
subscriptionType { name }
types {
...FullType
}
directives {
name
description
locations
args {
...InputValue
}
}
}
}
fragment FullType on __Type {
kind
name
description
fields(includeDeprecated: true) {
name
description
args {
...InputValue
}
type {
...TypeRef
}
isDeprecated
deprecationReason
}
inputFields {
...InputValue
}
interfaces {
...TypeRef
}
enumValues(includeDeprecated: true) {
name
description
isDeprecated
deprecationReason
}
possibleTypes {
...TypeRef
}
}
fragment InputValue on __InputValue {
name
description
type { ...TypeRef }
defaultValue
}
fragment TypeRef on __Type {
kind
name
ofType {
kind
name
ofType {
kind
name
ofType {
kind
name
ofType {
kind
name
ofType {
kind
name
ofType {
kind
name
ofType {
kind
name
}
}
}
}
}
}
}
}
`