/
field.go
116 lines (93 loc) · 2.15 KB
/
field.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
package graphql
import (
"strings"
"github.com/graphql-go/graphql"
)
// SetField sets the given field inside the given fields on the given path
func SetField(path string, fields graphql.Fields, field *graphql.Field) error {
if fields == nil || field == nil {
return nil
}
if IsNestedPath(path) {
parts := ParsePath(path)
key := parts[0]
target, has := fields[key]
if !has {
target = &graphql.Field{
Name: key,
Type: graphql.NewObject(graphql.ObjectConfig{
Name: key,
Fields: make(graphql.Fields),
}),
Resolve: func(p graphql.ResolveParams) (interface{}, error) {
return p.Source, nil
},
}
fields[key] = target
}
nested, is := target.Type.(*graphql.Object)
if !is {
return ErrTypeMismatch{
Type: key,
Expected: path,
}
}
err := SetFieldPath(nested, NewPath(parts[1:]), field)
if err != nil {
return err
}
return nil
}
fields[path] = field
return nil
}
// ParsePath returns the path as steps
func ParsePath(path string) []string {
return strings.Split(path, ".")
}
// NewPath constructs a new path of the given parts
func NewPath(parts []string) string {
return strings.Join(parts, ".")
}
// IsNestedPath checks whether the given value is a path
func IsNestedPath(value string) bool {
parts := strings.Split(value, ".")
if len(parts) == 1 {
return false
}
return true
}
// SetFieldPath sets the given field on the given path
func SetFieldPath(object *graphql.Object, path string, field *graphql.Field) error {
parts := ParsePath(path)
key := parts[0]
fields := object.Fields()
target, has := fields[key]
if len(parts) > 1 {
nested := graphql.NewObject(graphql.ObjectConfig{
Name: key,
Fields: make(graphql.Fields),
})
if has {
result, isObject := target.Type.(*graphql.Object)
if !isObject {
return ErrTypeMismatch{
Type: key,
Expected: path,
}
}
nested = result
}
return SetFieldPath(nested, NewPath(parts[1:]), field)
}
// Check if field is set and path has parts left
if has {
return ErrFieldAlreadySet{
Path: path,
Field: key,
}
}
object.AddFieldConfig(key, field)
object.Fields()
return nil
}