-
Notifications
You must be signed in to change notification settings - Fork 1.5k
/
wrappers.go
2011 lines (1757 loc) · 52.6 KB
/
wrappers.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
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 2019 Dgraph Labs, Inc. and 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 schema
import (
"bytes"
"encoding/json"
"fmt"
"net/http"
"net/url"
"reflect"
"sort"
"strconv"
"strings"
"text/scanner"
"github.com/vektah/gqlparser/v2/parser"
"github.com/dgraph-io/dgraph/x"
"github.com/pkg/errors"
"github.com/vektah/gqlparser/v2/ast"
)
// Wrap the github.com/vektah/gqlparser/ast defintions so that the bulk of the GraphQL
// algorithm and interface is dependent on behaviours we expect from a GraphQL schema
// and validation, but not dependent the exact structure in the gqlparser.
//
// This also auto hooks up some bookkeeping that's otherwise no fun. E.g. getting values for
// field arguments requires the variable map from the operation - so we'd need to carry vars
// through all the resolver functions. Much nicer if they are resolved by magic here.
// QueryType is currently supported queries
type QueryType string
// MutationType is currently supported mutations
type MutationType string
// FieldHTTPConfig contains the config needed to resolve a field using a remote HTTP endpoint
// which could a GraphQL or a REST endpoint.
type FieldHTTPConfig struct {
URL string
Method string
// would be nil if there is no body
Template *interface{}
Mode string
ForwardHeaders http.Header
// would be empty for non-GraphQL requests
RemoteGqlQueryName string
RemoteGqlQuery string
// args required by the HTTP/GraphQL request. These should be present in the parent type
// in the case of resolving a field or in the parent field in case of a query/mutation
RequiredArgs map[string]bool
// For the following request
// graphql: "query($sinput: [SchoolInput]) { schoolNames(schools: $sinput) }"
// the GraphqlBatchModeArgument would be sinput, we use it to know the GraphQL variable that
// we should send the data in.
GraphqlBatchModeArgument string
}
// Query/Mutation types and arg names
const (
GetQuery QueryType = "get"
FilterQuery QueryType = "query"
SchemaQuery QueryType = "schema"
PasswordQuery QueryType = "checkPassword"
HTTPQuery QueryType = "http"
NotSupportedQuery QueryType = "notsupported"
AddMutation MutationType = "add"
UpdateMutation MutationType = "update"
DeleteMutation MutationType = "delete"
HTTPMutation MutationType = "http"
NotSupportedMutation MutationType = "notsupported"
IDType = "ID"
IDArgName = "id"
InputArgName = "input"
FilterArgName = "filter"
)
// Schema represents a valid GraphQL schema
type Schema interface {
Operation(r *Request) (Operation, error)
Queries(t QueryType) []string
Mutations(t MutationType) []string
}
// An Operation is a single valid GraphQL operation. It contains either
// Queries or Mutations, but not both. Subscriptions are not yet supported.
type Operation interface {
Queries() []Query
Mutations() []Mutation
Schema() Schema
IsQuery() bool
IsMutation() bool
IsSubscription() bool
}
// A Field is one field from an Operation.
type Field interface {
Name() string
Alias() string
ResponseName() string
ArgValue(name string) interface{}
IsArgListType(name string) bool
IDArgValue() (*string, uint64, error)
XIDArg() string
SetArgTo(arg string, val interface{})
Skip() bool
Include() bool
Cascade() bool
HasCustomDirective() (bool, map[string]bool)
Type() Type
SelectionSet() []Field
Location() x.Location
DgraphPredicate() string
Operation() Operation
// InterfaceType tells us whether this field represents a GraphQL Interface.
InterfaceType() bool
IncludeInterfaceField(types []interface{}) bool
TypeName(dgraphTypes []interface{}) string
GetObjectName() string
IsAuthQuery() bool
CustomHTTPConfig() (FieldHTTPConfig, error)
EnumValues() []string
}
// A Mutation is a field (from the schema's Mutation type) from an Operation
type Mutation interface {
Field
MutationType() MutationType
MutatedType() Type
QueryField() Field
NumUidsField() Field
}
// A Query is a field (from the schema's Query type) from an Operation
type Query interface {
Field
QueryType() QueryType
Rename(newName string)
AuthFor(typ Type, jwtVars map[string]interface{}) Query
}
// A Type is a GraphQL type like: Float, T, T! and [T!]!. If it's not a list, then
// ListType is nil. If it's an object type then Field gets field definitions by
// name from the definition of the type; IDField gets the ID field of the type.
type Type interface {
Field(name string) FieldDefinition
Fields() []FieldDefinition
IDField() FieldDefinition
XIDField() FieldDefinition
InterfaceImplHasAuthRules() bool
PasswordField() FieldDefinition
Name() string
DgraphName() string
DgraphPredicate(fld string) string
Nullable() bool
ListType() Type
Interfaces() []string
EnsureNonNulls(map[string]interface{}, string) error
FieldOriginatedFrom(fieldName string) string
AuthRules() *TypeAuth
fmt.Stringer
}
// A FieldDefinition is a field as defined in some Type in the schema. As opposed
// to a Field, which is an instance of a query or mutation asking for a field
// (which in turn must have a FieldDefinition of the right type in the schema.)
type FieldDefinition interface {
Name() string
Type() Type
IsID() bool
Inverse() FieldDefinition
// TODO - It might be possible to get rid of ForwardEdge and just use Inverse() always.
ForwardEdge() FieldDefinition
}
type astType struct {
typ *ast.Type
inSchema *schema
dgraphPredicate map[string]map[string]string
}
type schema struct {
schema *ast.Schema
// dgraphPredicate gives us the dgraph predicate corresponding to a typeName + fieldName.
// It is pre-computed so that runtime queries and mutations can look it
// up quickly.
// The key for the first map are the type names. The second map has a mapping of the
// fieldName => dgraphPredicate.
dgraphPredicate map[string]map[string]string
// Map of mutation field name to mutated type.
mutatedType map[string]*astType
// Map from typename to ast.Definition
typeNameAst map[string][]*ast.Definition
// customDirectives stores the mapping of typeName -> fieldName -> @custom definition.
// It is read-only.
// The outer map will contain typeName key only if one of the fields on that type has @custom.
// The inner map will contain fieldName key only if that field has @custom.
// It is pre-computed so that runtime queries and mutations can look it up quickly, and not do
// something like field.Directives.ForName("custom"), which results in iterating over all the
// directives of the field.
customDirectives map[string]map[string]*ast.Directive
// Map from typename to auth rules
authRules map[string]*TypeAuth
}
type operation struct {
op *ast.OperationDefinition
vars map[string]interface{}
header http.Header
// The fields below are used by schema introspection queries.
query string
doc *ast.QueryDocument
inSchema *schema
}
type field struct {
field *ast.Field
op *operation
sel ast.Selection
// arguments contains the computed values for arguments taking into account the values
// for the GraphQL variables supplied in the query.
arguments map[string]interface{}
}
type fieldDefinition struct {
fieldDef *ast.FieldDefinition
inSchema *schema
dgraphPredicate map[string]map[string]string
}
type mutation field
type query field
func (s *schema) Queries(t QueryType) []string {
if s.schema.Query == nil {
return nil
}
var result []string
for _, q := range s.schema.Query.Fields {
if queryType(q.Name, s.customDirectives["Query"][q.Name]) == t {
result = append(result, q.Name)
}
}
return result
}
func (s *schema) Mutations(t MutationType) []string {
if s.schema.Mutation == nil {
return nil
}
var result []string
for _, m := range s.schema.Mutation.Fields {
if mutationType(m.Name, s.customDirectives["Mutation"][m.Name]) == t {
result = append(result, m.Name)
}
}
return result
}
func (o *operation) IsQuery() bool {
return o.op.Operation == ast.Query
}
func (o *operation) IsMutation() bool {
return o.op.Operation == ast.Mutation
}
func (o *operation) IsSubscription() bool {
return o.op.Operation == ast.Subscription
}
func (o *operation) Schema() Schema {
return o.inSchema
}
func (o *operation) Queries() (qs []Query) {
if o.IsMutation() {
return
}
for _, s := range o.op.SelectionSet {
if f, ok := s.(*ast.Field); ok {
qs = append(qs, &query{field: f, op: o, sel: s})
}
}
return
}
func (o *operation) Mutations() (ms []Mutation) {
if !o.IsMutation() {
return
}
for _, s := range o.op.SelectionSet {
if f, ok := s.(*ast.Field); ok {
ms = append(ms, &mutation{field: f, op: o})
}
}
return
}
// parentInterface returns the name of an interface that a field belonging to a type definition
// typDef inherited from. If there is no such interface, then it returns an empty string.
//
// Given the following schema
// interface A {
// name: String
// }
//
// type B implements A {
// name: String
// age: Int
// }
//
// calling parentInterface on the fieldName name with type definition for B, would return A.
func parentInterface(sch *ast.Schema, typDef *ast.Definition, fieldName string) *ast.Definition {
if len(typDef.Interfaces) == 0 {
return nil
}
for _, iface := range typDef.Interfaces {
interfaceDef := sch.Types[iface]
for _, interfaceField := range interfaceDef.Fields {
if fieldName == interfaceField.Name {
return interfaceDef
}
}
}
return nil
}
func parentInterfaceForPwdField(sch *ast.Schema, typDef *ast.Definition,
fieldName string) *ast.Definition {
if len(typDef.Interfaces) == 0 {
return nil
}
for _, iface := range typDef.Interfaces {
interfaceDef := sch.Types[iface]
pwdField := getPasswordField(interfaceDef)
if pwdField != nil && fieldName == pwdField.Name {
return interfaceDef
}
}
return nil
}
func convertPasswordDirective(dir *ast.Directive) *ast.FieldDefinition {
if dir.Name != "secret" {
return nil
}
name := dir.Arguments.ForName("field").Value.Raw
pred := dir.Arguments.ForName("pred")
dirs := ast.DirectiveList{}
if pred != nil {
dirs = ast.DirectiveList{{
Name: "dgraph",
Arguments: ast.ArgumentList{{
Name: "pred",
Value: &ast.Value{
Raw: pred.Value.Raw,
Kind: ast.StringValue,
},
}},
Position: dir.Position,
}}
}
fd := &ast.FieldDefinition{
Name: name,
Type: &ast.Type{
NamedType: "String",
NonNull: true,
Position: dir.Position,
},
Directives: dirs,
Position: dir.Position,
}
return fd
}
func dgraphMapping(sch *ast.Schema) map[string]map[string]string {
const (
add = "Add"
update = "Update"
del = "Delete"
payload = "Payload"
)
dgraphPredicate := make(map[string]map[string]string)
for _, inputTyp := range sch.Types {
// We only want to consider input types (object and interface) defined by the user as part
// of the schema hence we ignore BuiltIn, query and mutation types.
if inputTyp.BuiltIn || isQueryOrMutationType(inputTyp) || inputTyp.Name == "Subscription" ||
(inputTyp.Kind != ast.Object && inputTyp.Kind != ast.Interface) {
continue
}
originalTyp := inputTyp
inputTypeName := inputTyp.Name
if strings.HasPrefix(inputTypeName, add) && strings.HasSuffix(inputTypeName, payload) {
continue
}
dgraphPredicate[originalTyp.Name] = make(map[string]string)
if (strings.HasPrefix(inputTypeName, update) || strings.HasPrefix(inputTypeName, del)) &&
strings.HasSuffix(inputTypeName, payload) {
// For UpdateTypePayload and DeleteTypePayload, inputTyp should be Type.
if strings.HasPrefix(inputTypeName, update) {
inputTypeName = strings.TrimSuffix(strings.TrimPrefix(inputTypeName, update),
payload)
} else if strings.HasPrefix(inputTypeName, del) {
inputTypeName = strings.TrimSuffix(strings.TrimPrefix(inputTypeName, del), payload)
}
inputTyp = sch.Types[inputTypeName]
}
// We add password field to the cached type information to be used while opening
// resolving and rewriting queries to be sent to dgraph. Otherwise, rewriter won't
// know what the password field in AddInputType/ TypePatch/ TypeRef is.
var fields ast.FieldList
fields = append(fields, inputTyp.Fields...)
for _, directive := range inputTyp.Directives {
fd := convertPasswordDirective(directive)
if fd == nil {
continue
}
fields = append(fields, fd)
}
for _, fld := range fields {
if isID(fld) {
// We don't need a mapping for the field, as we the dgraph predicate for them is
// fixed i.e. uid.
continue
}
typName := typeName(inputTyp)
parentInt := parentInterface(sch, inputTyp, fld.Name)
if parentInt != nil {
typName = typeName(parentInt)
}
// 1. For fields that have @dgraph(pred: xxxName) directive, field name would be
// xxxName.
// 2. For fields where the type (or underlying interface) has a @dgraph(type: xxxName)
// directive, field name would be xxxName.fldName.
//
// The cases below cover the cases where neither the type or field have @dgraph
// directive.
// 3. For types which don't inherit from an interface the keys, value would be.
// typName,fldName => typName.fldName
// 4. For types which inherit fields from an interface
// typName,fldName => interfaceName.fldName
// 5. For DeleteTypePayload type
// DeleteTypePayload,fldName => typName.fldName
fname := fieldName(fld, typName)
dgraphPredicate[originalTyp.Name][fld.Name] = fname
}
}
return dgraphPredicate
}
func mutatedTypeMapping(s *schema,
dgraphPredicate map[string]map[string]string) map[string]*astType {
if s.schema.Mutation == nil {
return nil
}
m := make(map[string]*astType, len(s.schema.Mutation.Fields))
for _, field := range s.schema.Mutation.Fields {
mutatedTypeName := ""
switch {
case strings.HasPrefix(field.Name, "add"):
mutatedTypeName = strings.TrimPrefix(field.Name, "add")
case strings.HasPrefix(field.Name, "update"):
mutatedTypeName = strings.TrimPrefix(field.Name, "update")
case strings.HasPrefix(field.Name, "delete"):
mutatedTypeName = strings.TrimPrefix(field.Name, "delete")
default:
}
// This is a convoluted way of getting the type for mutatedTypeName. We get the definition
// for UpdateTPayload and get the type from the first field. There is no direct way to get
// the type from the definition of an object. We use Update and not Add here because
// Interfaces only have Update.
var def *ast.Definition
if def = s.schema.Types["Update"+mutatedTypeName+"Payload"]; def == nil {
def = s.schema.Types["Add"+mutatedTypeName+"Payload"]
}
if def == nil {
continue
}
// Accessing 0th element should be safe to do as according to the spec an object must define
// one or more fields.
typ := def.Fields[0].Type
// This would contain mapping of mutation field name to the Type()
// for e.g. addPost => astType for Post
m[field.Name] = &astType{typ, s, dgraphPredicate}
}
return m
}
func typeMappings(s *ast.Schema) map[string][]*ast.Definition {
typeNameAst := make(map[string][]*ast.Definition)
for _, typ := range s.Types {
name := typeName(typ)
typeNameAst[name] = append(typeNameAst[name], typ)
}
return typeNameAst
}
func customMappings(s *ast.Schema) map[string]map[string]*ast.Directive {
customDirectives := make(map[string]map[string]*ast.Directive)
for _, typ := range s.Types {
for _, field := range typ.Fields {
for i, dir := range field.Directives {
if dir.Name == customDirective {
// remove custom directive from s
lastIndex := len(field.Directives) - 1
field.Directives[i] = field.Directives[lastIndex]
field.Directives = field.Directives[:lastIndex]
// now put it into mapping
var fieldMap map[string]*ast.Directive
if innerMap, ok := customDirectives[typ.Name]; !ok {
fieldMap = make(map[string]*ast.Directive)
} else {
fieldMap = innerMap
}
fieldMap[field.Name] = dir
customDirectives[typ.Name] = fieldMap
// break, as there can only be one @custom
break
}
}
}
}
return customDirectives
}
// AsSchema wraps a github.com/vektah/gqlparser/ast.Schema.
func AsSchema(s *ast.Schema) (Schema, error) {
// Auth rules can't be effectively validated as part of the normal rules -
// because they need the fully generated schema to be checked against.
authRules, err := authRules(s)
if err != nil {
return nil, err
}
dgraphPredicate := dgraphMapping(s)
sch := &schema{
schema: s,
dgraphPredicate: dgraphPredicate,
typeNameAst: typeMappings(s),
customDirectives: customMappings(s),
authRules: authRules,
}
sch.mutatedType = mutatedTypeMapping(sch, dgraphPredicate)
return sch, nil
}
func responseName(f *ast.Field) string {
if f.Alias == "" {
return f.Name
}
return f.Alias
}
func (f *field) Name() string {
return f.field.Name
}
func (f *field) Alias() string {
return f.field.Alias
}
func (f *field) ResponseName() string {
return responseName(f.field)
}
func (f *field) SetArgTo(arg string, val interface{}) {
if f.arguments == nil {
f.arguments = make(map[string]interface{})
}
f.arguments[arg] = val
// If the argument doesn't exist, add it to the list. It is used later on to get
// parameters. Value isn't required because it's fetched using the arguments map.
argument := f.field.Arguments.ForName(arg)
if argument == nil {
f.field.Arguments = append(f.field.Arguments, &ast.Argument{Name: arg})
}
}
func (f *field) IsAuthQuery() bool {
return f.field.Arguments.ForName("dgraph.uid") != nil
}
func (f *field) ArgValue(name string) interface{} {
if f.arguments == nil {
// Compute and cache the map first time this function is called for a field.
f.arguments = f.field.ArgumentMap(f.op.vars)
}
return f.arguments[name]
}
func (f *field) IsArgListType(name string) bool {
arg := f.field.Arguments.ForName(name)
if arg == nil {
return false
}
return arg.Value.ExpectedType.Elem != nil
}
func (f *field) Skip() bool {
dir := f.field.Directives.ForName("skip")
if dir == nil {
return false
}
return dir.ArgumentMap(f.op.vars)["if"].(bool)
}
func (f *field) Include() bool {
dir := f.field.Directives.ForName("include")
if dir == nil {
return true
}
return dir.ArgumentMap(f.op.vars)["if"].(bool)
}
func (f *field) Cascade() bool {
return f.field.Directives.ForName(cascadeDirective) != nil
}
func (f *field) HasCustomDirective() (bool, map[string]bool) {
custom := f.op.inSchema.customDirectives[f.GetObjectName()][f.Name()]
if custom == nil {
return false, nil
}
var rf map[string]bool
httpArg := custom.Arguments.ForName("http")
bodyArg := httpArg.Value.Children.ForName("body")
if bodyArg != nil {
bodyTemplate := bodyArg.Raw
_, rf, _ = parseBodyTemplate(bodyTemplate)
}
if rf == nil {
rf = make(map[string]bool)
}
rawURL := httpArg.Value.Children.ForName("url").Raw
// Error here should be nil as we should have parsed and validated the URL
// already.
u, _ := url.Parse(rawURL)
// Parse variables from the path and query params.
elems := strings.Split(u.Path, "/")
for _, elem := range elems {
if strings.HasPrefix(elem, "$") {
rf[elem[1:]] = true
}
}
for k := range u.Query() {
val := u.Query().Get(k)
if strings.HasPrefix(val, "$") {
rf[val[1:]] = true
}
}
graphqlArg := httpArg.Value.Children.ForName("graphql")
if graphqlArg == nil {
return true, rf
}
modeVal := ""
modeArg := httpArg.Value.Children.ForName(mode)
if modeArg != nil {
modeVal = modeArg.Raw
}
if modeVal == SINGLE {
// For BATCH mode, required args would have been parsed from the body above.
var err error
rf, err = parseRequiredArgsFromGQLRequest(graphqlArg.Raw)
// This should not be returning an error since we should have validated this during schema
// update.
if err != nil {
return true, nil
}
}
return true, rf
}
func (f *field) XIDArg() string {
xidArgName := ""
passwordField := f.Type().PasswordField()
for _, arg := range f.field.Arguments {
if arg.Name != IDArgName && (passwordField == nil ||
arg.Name != passwordField.Name()) {
xidArgName = arg.Name
}
}
return f.Type().DgraphPredicate(xidArgName)
}
func (f *field) IDArgValue() (xid *string, uid uint64, err error) {
idField := f.Type().IDField()
passwordField := f.Type().PasswordField()
xidArgName := ""
// This method is only called for Get queries and check. These queries can accept ID, XID
// or Password. Therefore the non ID and Password field is an XID.
// TODO maybe there is a better way to do this.
for _, arg := range f.field.Arguments {
if (idField == nil || arg.Name != idField.Name()) &&
(passwordField == nil || arg.Name != passwordField.Name()) {
xidArgName = arg.Name
}
}
if xidArgName != "" {
xidArgVal, ok := f.ArgValue(xidArgName).(string)
pos := f.field.GetPosition()
if !ok {
err = x.GqlErrorf("Argument (%s) of %s was not able to be parsed as a string",
xidArgName, f.Name()).WithLocations(x.Location{Line: pos.Line, Column: pos.Column})
return
}
xid = &xidArgVal
}
if idField == nil {
return
}
idArg := f.ArgValue(idField.Name())
if idArg != nil {
id, ok := idArg.(string)
var ierr error
uid, ierr = strconv.ParseUint(id, 0, 64)
if !ok || ierr != nil {
pos := f.field.GetPosition()
err = x.GqlErrorf("ID argument (%s) of %s was not able to be parsed", id, f.Name()).
WithLocations(x.Location{Line: pos.Line, Column: pos.Column})
return
}
}
return
}
func (f *field) Type() Type {
var t *ast.Type
if f.field != nil && f.field.Definition != nil {
// This is strange. There was a case with a parsed schema and query where the field
// had a nil Definition ... how ???
t = f.field.Definition.Type
}
return &astType{
typ: t,
inSchema: f.op.inSchema,
dgraphPredicate: f.op.inSchema.dgraphPredicate,
}
}
func (f *field) InterfaceType() bool {
return f.op.inSchema.schema.Types[f.field.Definition.Type.Name()].Kind == ast.Interface
}
func (f *field) GetObjectName() string {
return f.field.ObjectDefinition.Name
}
func getCustomHTTPConfig(f *field, isQueryOrMutation bool) (FieldHTTPConfig, error) {
custom := f.op.inSchema.customDirectives[f.GetObjectName()][f.Name()]
httpArg := custom.Arguments.ForName("http")
fconf := FieldHTTPConfig{
URL: httpArg.Value.Children.ForName("url").Raw,
Method: httpArg.Value.Children.ForName("method").Raw,
}
fconf.Mode = SINGLE
op := httpArg.Value.Children.ForName(mode)
if op != nil {
fconf.Mode = op.Raw
}
// both body and graphql can't be present together
bodyArg := httpArg.Value.Children.ForName("body")
graphqlArg := httpArg.Value.Children.ForName("graphql")
var bodyTemplate string
if bodyArg != nil {
bodyTemplate = bodyArg.Raw
} else if graphqlArg != nil {
bodyTemplate = `{ query: $query, variables: $variables }`
}
// bodyTemplate will be empty if there was no body or graphql, like the case of a simple GET req
if bodyTemplate != "" {
bt, rf, err := parseBodyTemplate(bodyTemplate)
if err != nil {
return fconf, err
}
fconf.Template = bt
fconf.RequiredArgs = rf
}
if !isQueryOrMutation && graphqlArg != nil && fconf.Mode == SINGLE {
// For BATCH mode, required args would have been parsed from the body above.
// Safe to ignore the error here since we should already have validated that we can parse
// the required args from the GraphQL request during schema update.
fconf.RequiredArgs, _ = parseRequiredArgsFromGQLRequest(graphqlArg.Raw)
}
fconf.ForwardHeaders = http.Header{}
secretHeaders := httpArg.Value.Children.ForName("secretHeaders")
if secretHeaders != nil {
hc.RLock()
for _, h := range secretHeaders.Children {
key := strings.Split(h.Value.Raw, ":")
if len(key) == 1 {
key = []string{h.Value.Raw, h.Value.Raw}
} else if len(key) > 2 {
continue
}
val := string(hc.secrets[key[1]])
fconf.ForwardHeaders.Set(key[0], val)
}
hc.RUnlock()
}
forwardHeaders := httpArg.Value.Children.ForName("forwardHeaders")
if forwardHeaders != nil {
for _, h := range forwardHeaders.Children {
// We would override the header if it was also specified as part of secretHeaders.
key := strings.Split(h.Value.Raw, ":")
if len(key) == 1 {
key = []string{h.Value.Raw, h.Value.Raw}
} else if len(key) > 2 {
continue
}
reqHeaderVal := f.op.header.Get(key[1])
fconf.ForwardHeaders.Set(key[0], reqHeaderVal)
}
}
if graphqlArg != nil {
queryDoc, gqlErr := parser.ParseQuery(&ast.Source{Input: graphqlArg.Raw})
if gqlErr != nil {
return fconf, gqlErr
}
// queryDoc will always have only one operation with only one field
qfield := queryDoc.Operations[0].SelectionSet[0].(*ast.Field)
if fconf.Mode == BATCH {
fconf.GraphqlBatchModeArgument = queryDoc.Operations[0].VariableDefinitions[0].Variable
}
fconf.RemoteGqlQueryName = qfield.Name
buf := &bytes.Buffer{}
buildGraphqlRequestFields(buf, f.field)
remoteQuery := graphqlArg.Raw
remoteQuery = remoteQuery[:strings.LastIndex(remoteQuery, "}")]
remoteQuery = fmt.Sprintf("%s%s}", remoteQuery, buf.String())
fconf.RemoteGqlQuery = remoteQuery
}
// if it is a query or mutation, substitute the vars in URL and Body here itself
if isQueryOrMutation {
var err error
argMap := f.field.ArgumentMap(f.op.vars)
var bodyVars map[string]interface{}
// url params can exist only with body, and not with graphql
if graphqlArg == nil {
fconf.URL, err = SubstituteVarsInURL(fconf.URL, argMap)
if err != nil {
return fconf, errors.Wrapf(err, "while substituting vars in URL")
}
bodyVars = argMap
} else {
bodyVars = make(map[string]interface{})
bodyVars["query"] = fconf.RemoteGqlQuery
bodyVars["variables"] = argMap
}
if fconf.Template != nil {
if err = SubstituteVarsInBody(fconf.Template, bodyVars); err != nil {
return fconf, errors.Wrapf(err, "while substituting vars in Body")
}
}
}
return fconf, nil
}
func (f *field) CustomHTTPConfig() (FieldHTTPConfig, error) {
return getCustomHTTPConfig(f, false)
}
func (f *field) EnumValues() []string {
typ := f.Type()
def := f.op.inSchema.schema.Types[typ.Name()]
res := make([]string, 0, len(def.EnumValues))
for _, e := range def.EnumValues {
res = append(res, e.Name)
}
return res
}
func (f *field) SelectionSet() (flds []Field) {
for _, s := range f.field.SelectionSet {
if fld, ok := s.(*ast.Field); ok {
flds = append(flds, &field{
field: fld,
op: f.op,
})
}
}
return
}
func (f *field) Location() x.Location {
return x.Location{
Line: f.field.Position.Line,
Column: f.field.Position.Column}
}
func (f *field) Operation() Operation {
return f.op
}
func (f *field) DgraphPredicate() string {
return f.op.inSchema.dgraphPredicate[f.field.ObjectDefinition.Name][f.Name()]
}
func (f *field) TypeName(dgraphTypes []interface{}) string {
for _, typ := range dgraphTypes {
styp, ok := typ.(string)
if !ok {
continue
}
for _, origTyp := range f.op.inSchema.typeNameAst[styp] {
if origTyp.Kind != ast.Object {
continue
}
return origTyp.Name
}
}
return ""
}
func (f *field) IncludeInterfaceField(dgraphTypes []interface{}) bool {
// As ID maps to uid in dgraph, so it is not stored as an edge, hence does not appear in
// f.op.inSchema.dgraphPredicate map. So, always include the queried field if it is of ID type.
if f.Type().Name() == IDType {
return true
}
// Given a list of dgraph types, we query the schema and find the one which is an ast.Object
// and not an Interface object.
for _, typ := range dgraphTypes {
styp, ok := typ.(string)
if !ok {
continue
}
for _, origTyp := range f.op.inSchema.typeNameAst[styp] {
if origTyp.Kind == ast.Object {
// If the field doesn't exist in the map corresponding to the object type, then we
// don't need to include it.
_, ok := f.op.inSchema.dgraphPredicate[origTyp.Name][f.Name()]
return ok || f.Name() == Typename
}