-
Notifications
You must be signed in to change notification settings - Fork 0
/
Document.go
89 lines (68 loc) · 1.85 KB
/
Document.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
package graphql
import (
"reflect"
)
// Document represents a GraphQL request.
type Document struct {
Operation *Operation
}
// Execute executes the operations defined in the GraphQL document.
func (document *Document) Execute(api *API) *Response {
var data interface{}
var allErrors []string
if document.Operation != nil {
data, allErrors = resolve(document.Operation, nil, api)
}
return &Response{
Data: data,
Errors: allErrors,
}
}
func resolve(container FieldContainer, parent interface{}, api *API) (Map, []string) {
var allErrors []string
var errors []string
data := Map{}
for _, field := range container.Fields() {
obj, err := field.Resolve(parent, api)
if err != nil {
allErrors = append(allErrors, err.Error())
}
value := reflect.Indirect(reflect.ValueOf(obj))
kind := value.Kind()
switch kind {
case reflect.Slice:
// Simple types can be inserted instantly
sliceType := value.Type()
sliceElementKind := sliceType.Elem().Kind()
if sliceElementKind != reflect.Interface && sliceElementKind != reflect.Ptr && sliceElementKind != reflect.Struct {
data[field.name] = obj
continue
}
// If we have complex types as elements and we didn't specify a field, skip it
if len(field.fields) == 0 {
continue
}
// Create a slice with the data we requested
slice := make([]Map, value.Len())
for i := 0; i < value.Len(); i++ {
element := value.Index(i).Interface()
slice[i], errors = resolve(field, element, api)
if errors != nil {
allErrors = append(allErrors, errors...)
}
}
data[field.name] = slice
case reflect.Struct:
if len(field.fields) == 0 {
continue
}
data[field.name], errors = resolve(field, obj, api)
if errors != nil {
allErrors = append(allErrors, errors...)
}
default:
data[field.name] = obj
}
}
return data, allErrors
}