-
Notifications
You must be signed in to change notification settings - Fork 0
/
list.go
132 lines (103 loc) · 2.34 KB
/
list.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
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
package gq
import (
"encoding/json"
"fmt"
"reflect"
"strconv"
"github.com/aacebo/gq/query"
)
type List struct {
Type Schema `json:"type,omitempty"`
Use []Middleware `json:"-"`
}
func (self List) Key() string {
return fmt.Sprintf("List[%s]", self.Type.Key())
}
func (self List) Do(params *DoParams) Result {
parser := query.Parser([]byte(params.Query))
query, err := parser.Parse()
if err != nil {
return Result{Error: err}
}
return self.Resolve(&ResolveParams{
Query: query,
Value: params.Value,
Context: params.Context,
})
}
func (self List) Resolve(params *ResolveParams) Result {
res := Result{}
routes := []Middleware{}
if self.Use != nil {
for _, route := range self.Use {
routes = append(routes, route)
}
}
routes = append(routes, self.resolve)
var next Resolver
i := -1
next = func(params *ResolveParams) Result {
i++
if i > (len(routes) - 1) {
return Result{}
}
return routes[i](params, next)
}
result := next(&ResolveParams{
Query: params.Query,
Parent: params.Parent,
Key: "items",
Value: params.Value,
Context: params.Context,
})
if result.Error != nil {
res.Error = NewEmptyError(params.Key).Add(result.Error)
return res
}
res.Meta = result.Meta
res.Data = result.Data
return res
}
func (self List) resolve(params *ResolveParams, _ Resolver) Result {
value := reflect.Indirect(reflect.ValueOf(params.Value))
res := Result{}
if !value.IsValid() {
return res
}
if value.Kind() != reflect.Array && value.Kind() != reflect.Slice {
res.Error = NewError(params.Key, "must be an array/slice")
return res
}
err := NewEmptyError(params.Key)
for i := 0; i < value.Len(); i++ {
key := strconv.Itoa(i)
index := value.Index(i)
result := self.Type.Resolve(&ResolveParams{
Query: params.Query,
Parent: params.Value,
Key: key,
Value: index.Interface(),
Context: params.Context,
})
if result.Error != nil {
err = err.Add(result.Error)
continue
}
index.Set(reflect.ValueOf(result.Data))
if result.Meta != nil && !result.Meta.Empty() {
res.SetMeta(key, result.Meta)
}
}
if len(err.Errors) > 0 {
res.Error = err
return res
}
if res.Meta != nil && res.Meta.Empty() {
res.Meta = nil
}
res.Data = value.Interface()
return res
}
func (self List) MarshalJSON() ([]byte, error) {
return json.Marshal(self.Key())
}