-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathgraphql.go
More file actions
84 lines (71 loc) · 2.27 KB
/
graphql.go
File metadata and controls
84 lines (71 loc) · 2.27 KB
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
package graphql
import (
"context"
"github.com/sprucehealth/graphql/gqlerrors"
"github.com/sprucehealth/graphql/language/ast"
"github.com/sprucehealth/graphql/language/parser"
"github.com/sprucehealth/graphql/language/source"
)
type Params struct {
// Schema is the GraphQL type system to use when validating and executing a query.
Schema Schema
// RequestString is a GraphQL language formatted string representing the requested operation.
RequestString string
// RootObject is the value provided as the first argument to resolver functions on the top
// level type (e.g. the query object type).
RootObject map[string]any
// VariableValues is a mapping of variable name to runtime value to use for all variables
// defined in the requestString.
VariableValues map[string]any
// OperationName is the name of the operation to use if requestString contains multiple
// possible operations. Can be omitted if requestString contains only
// one operation.
OperationName string
// Tracer if set is called after each invocation of a custom resolver with the duration.
Tracer Tracer
}
func Do(ctx context.Context, p Params) *Result {
source := source.New("GraphQL request", p.RequestString)
ast, err := parser.Parse(parser.ParseParams{Source: source})
if err != nil {
return &Result{
Errors: gqlerrors.FormatErrors(err),
}
}
validationResult := ValidateDocument(&p.Schema, ast, nil)
if !validationResult.IsValid {
return &Result{
Errors: validationResult.Errors,
}
}
return Execute(ctx, ExecuteParams{
Schema: p.Schema,
Root: p.RootObject,
AST: ast,
OperationName: p.OperationName,
Args: p.VariableValues,
Tracer: p.Tracer,
})
}
// RequestTypeNames rewrites an ast document to include __typename
// in all selection sets.
func RequestTypeNames(doc *ast.Document) {
for _, node := range doc.Definitions {
if od, ok := node.(*ast.OperationDefinition); ok {
requestTypeNamesInSelectionSet(od.SelectionSet)
}
}
}
func requestTypeNamesInSelectionSet(ss *ast.SelectionSet) {
if ss == nil {
return
}
ss.Selections = append(ss.Selections, &ast.Field{
Name: &ast.Name{
Value: "__typename",
},
})
for _, selections := range ss.Selections {
requestTypeNamesInSelectionSet(selections.GetSelectionSet())
}
}