forked from wundergraph/graphql-go-tools
/
normalization.go
68 lines (52 loc) · 1.63 KB
/
normalization.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
package graphql
import (
"github.com/TykTechnologies/graphql-go-tools/v2/pkg/astnormalization"
"github.com/TykTechnologies/graphql-go-tools/v2/pkg/operationreport"
)
type NormalizationResult struct {
Successful bool
Errors Errors
}
func (r *Request) Normalize(schema *Schema) (result NormalizationResult, err error) {
if schema == nil {
return NormalizationResult{Successful: false, Errors: nil}, ErrNilSchema
}
report := r.parseQueryOnce()
if report.HasErrors() {
return normalizationResultFromReport(report)
}
r.document.Input.Variables = r.Variables
normalizer := astnormalization.NewWithOpts(
astnormalization.WithExtractVariables(),
astnormalization.WithRemoveFragmentDefinitions(),
astnormalization.WithRemoveUnusedVariables(),
astnormalization.WithInlineFragmentSpreads(),
)
if r.OperationName != "" {
normalizer.NormalizeNamedOperation(&r.document, &schema.document, []byte(r.OperationName), &report)
} else {
normalizer.NormalizeOperation(&r.document, &schema.document, &report)
}
if report.HasErrors() {
return normalizationResultFromReport(report)
}
r.isNormalized = true
r.Variables = r.document.Input.Variables
return NormalizationResult{Successful: true, Errors: nil}, nil
}
func normalizationResultFromReport(report operationreport.Report) (NormalizationResult, error) {
result := NormalizationResult{
Successful: false,
Errors: nil,
}
if !report.HasErrors() {
result.Successful = true
return result, nil
}
result.Errors = RequestErrorsFromOperationReport(report)
var err error
if len(report.InternalErrors) > 0 {
err = report.InternalErrors[0]
}
return result, err
}