forked from wundergraph/graphql-go-tools
-
Notifications
You must be signed in to change notification settings - Fork 4
/
extractor.go
101 lines (83 loc) · 2.32 KB
/
extractor.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
package graphql
import (
"bytes"
"github.com/TykTechnologies/graphql-go-tools/v2/pkg/ast"
"github.com/TykTechnologies/graphql-go-tools/v2/pkg/astvisitor"
"github.com/TykTechnologies/graphql-go-tools/v2/pkg/operationreport"
)
type Extractor struct {
walker *astvisitor.Walker
visitor *requestVisitor
}
func NewExtractor() *Extractor {
walker := astvisitor.NewWalker(48)
visitor := requestVisitor{
Walker: &walker,
}
walker.RegisterEnterFieldVisitor(&visitor)
walker.RegisterEnterOperationVisitor(&visitor)
return &Extractor{
walker: &walker,
visitor: &visitor,
}
}
func (e *Extractor) ExtractFieldsFromRequest(request *Request, schema *Schema, report *operationreport.Report, data RequestTypes) {
if !request.IsNormalized() {
result, err := request.Normalize(schema)
if err != nil {
report.AddInternalError(err)
}
if !result.Successful {
report.AddInternalError(result.Errors)
}
}
e.visitor.data = data
e.visitor.operation = &request.document
e.visitor.definition = &schema.document
e.walker.Walk(&request.document, &schema.document, report)
}
func (e *Extractor) ExtractFieldsFromRequestSingleOperation(request *Request, schema *Schema, report *operationreport.Report, data RequestTypes) {
e.visitor.singleOperation = true
e.visitor.operationName = request.OperationName
e.ExtractFieldsFromRequest(request, schema, report, data)
}
type requestVisitor struct {
singleOperation, shouldSkip bool
operationName string
*astvisitor.Walker
operation, definition *ast.Document
data RequestTypes
}
func (p *requestVisitor) EnterOperationDefinition(ref int) {
if !p.singleOperation {
return
}
if p.operationName == "" && ref == 0 {
p.shouldSkip = false
return
} else if p.operationName == "" && ref != 0 {
p.shouldSkip = true
return
}
opName := p.operation.OperationDefinitionNameBytes(ref)
if bytes.Equal(opName, []byte(p.operationName)) {
p.shouldSkip = false
} else {
p.shouldSkip = true
}
}
func (p *requestVisitor) EnterField(ref int) {
if p.shouldSkip {
return
}
fieldName := p.operation.FieldNameString(ref)
parentTypeName := p.definition.NodeNameString(p.EnclosingTypeDefinition)
t, ok := p.data[parentTypeName]
if !ok {
t = make(RequestFields)
}
if _, ok := t[fieldName]; !ok {
t[fieldName] = struct{}{}
}
p.data[parentTypeName] = t
}