-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
context_field_input.go
85 lines (69 loc) · 2 KB
/
context_field_input.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
package graphql
import (
"context"
"github.com/vektah/gqlparser/v2/ast"
"github.com/vektah/gqlparser/v2/gqlerror"
)
const fieldInputCtx key = "field_input_context"
type FieldInputContext struct {
ParentField *FieldContext
ParentInput *FieldInputContext
Field *string
Index *int
}
func (fic *FieldInputContext) Path() ast.Path {
var inputPath ast.Path
for it := fic; it != nil; it = it.ParentInput {
if it.Index != nil {
inputPath = append(inputPath, ast.PathIndex(*it.Index))
} else if it.Field != nil {
inputPath = append(inputPath, ast.PathName(*it.Field))
}
}
// because we are walking up the chain, all the elements are backwards, do an inplace flip.
for i := len(inputPath)/2 - 1; i >= 0; i-- {
opp := len(inputPath) - 1 - i
inputPath[i], inputPath[opp] = inputPath[opp], inputPath[i]
}
if fic.ParentField != nil {
fieldPath := fic.ParentField.Path()
return append(fieldPath, inputPath...)
}
return inputPath
}
func NewFieldInputWithField(field string) *FieldInputContext {
return &FieldInputContext{Field: &field}
}
func NewFieldInputWithIndex(index int) *FieldInputContext {
return &FieldInputContext{Index: &index}
}
func WithFieldInputContext(ctx context.Context, fic *FieldInputContext) context.Context {
if fieldContext := GetFieldContext(ctx); fieldContext != nil {
fic.ParentField = fieldContext
}
if fieldInputContext := GetFieldInputContext(ctx); fieldInputContext != nil {
fic.ParentInput = fieldInputContext
}
return context.WithValue(ctx, fieldInputCtx, fic)
}
func GetFieldInputContext(ctx context.Context) *FieldInputContext {
if val, ok := ctx.Value(fieldInputCtx).(*FieldInputContext); ok {
return val
}
return nil
}
func WrapErrorWithInputPath(ctx context.Context, err error) error {
if err == nil {
return nil
}
inputContext := GetFieldInputContext(ctx)
path := inputContext.Path()
if gerr, ok := err.(*gqlerror.Error); ok {
if gerr.Path == nil {
gerr.Path = path
}
return gerr
} else {
return gqlerror.WrapPath(path, err)
}
}