This repository has been archived by the owner on Jan 28, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathrouter.go
350 lines (299 loc) · 7.66 KB
/
router.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
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
package tools
import (
"encoding/json"
"errors"
"reflect"
"strings"
"github.com/arvitaly/graphql"
"github.com/graphql-go/graphql/language/ast"
"golang.org/x/net/context"
)
const (
ArgTypeParams = 1
ArgTypeSource = 2
ArgTypeArgs = 3
ArgTypeContext = 4
)
type ResolveParams struct {
FieldInfo FieldInfo
Source interface{}
Args interface{}
Context interface{}
Params graphql.ResolveParams
}
type Router struct {
queries map[string]RouteParams
resolves map[string]RouteParams
uses []UseFn
}
type RouteParams struct {
Args []int
Context reflect.Type
Handle interface{}
}
func NewRouter() *Router {
router := Router{
queries: map[string]RouteParams{},
resolves: map[string]RouteParams{},
uses: []UseFn{},
}
return &router
}
func (r *Router) Routes() map[string]interface{} {
routes := map[string]interface{}{}
for k, _ := range r.queries {
routes[k] = r.Resolve
}
return routes
}
func (r *Router) IsResolve(sourceType reflect.Type, field reflect.StructField) bool {
path := sourceType.Name() + "." + field.Name
if _, ok := r.queries[path]; ok {
return true
}
resolveTag := field.Tag.Get("resolve")
if resolveTag != "" {
resolveTagParams := strings.Split(resolveTag, ",")
if resolve, ok := r.resolves[resolveTagParams[0]]; ok {
r.queries[path] = resolve
return true
}
}
method, ok := sourceType.MethodByName("Resolve" + field.Name)
if ok {
r.Query(path, method.Func.Interface())
return true
}
return false
}
/**
**/
func (r *Router) SourceForResolve(fieldInfo FieldInfo, p graphql.ResolveParams) (interface{}, error) {
if reflect.TypeOf(p.Source).Kind() == reflect.Map {
sourceType := reflect.TypeOf(fieldInfo.Source)
if sourceType.Kind() == reflect.Ptr {
return reflect.New(sourceType).Interface(), nil
} else {
return reflect.New(sourceType).Elem().Interface(), nil
}
}
return p.Source, nil
sourceType := reflect.TypeOf(fieldInfo.Source)
sourceValueType := reflect.TypeOf(p.Source)
//Change ptr to elem
if sourceType.Kind() == reflect.Ptr {
sourceType = sourceType.Elem()
}
var source interface{}
//Check type of source
if sourceValueType.Kind() == reflect.Ptr {
source = reflect.ValueOf(p.Source).Elem().Interface()
} else {
if sourceValueType.Kind() != reflect.Struct {
if sourceValueType.Kind() == reflect.Map {
source = reflect.New(sourceType).Elem().Interface()
} else {
return nil, InvalidSourceError{RouterError{Text: "Source for resolve query should be struct or pointer to struct, has " + sourceValueType.Name()}}
}
} else {
source = p.Source
}
}
return source, nil
}
func (r *Router) Resolve(fieldInfo FieldInfo, p graphql.ResolveParams) (interface{}, error) {
source, err := r.SourceForResolve(fieldInfo, p)
if err != nil {
return nil, err
}
for _, useFn := range r.uses {
res, next, err := useFn(ResolveParams{
FieldInfo: fieldInfo,
Params: p,
Source: source,
})
if err != nil {
return nil, err
}
if !next {
return res, nil
}
}
if p.Info.Operation.GetOperation() != ast.OperationTypeSubscription {
res, err := r.ResolveQuery(fieldInfo, p)
if err != nil {
return nil, err
}
return res, nil
}
return nil, errors.New("Unsupported resolve")
}
func (r *Router) ResolveQuery(fieldInfo FieldInfo, p graphql.ResolveParams) (interface{}, error) {
source, err := r.SourceForResolve(fieldInfo, p)
if err != nil {
return nil, err
}
sourceType := reflect.TypeOf(source)
query, ok := r.queries[fieldInfo.Path]
if !ok {
return nil, NotFoundRoute{RouterError{Text: "Not found route for path " + fieldInfo.Path + " by source " + sourceType.Name() + "," + sourceType.Kind().String()}}
}
var args interface{}
if fieldInfo.Args != nil {
//args = getArgsForResolve(p.Args, reflect.TypeOf(fieldInfo.Args)).Interface()
outArgs := reflect.New(reflect.TypeOf(fieldInfo.Args))
err := MapToStruct(p.Args, outArgs.Interface())
if err != nil {
return nil, errors.New("Invalid args " + err.Error())
}
args = outArgs.Elem().Interface()
} else {
args = nil
}
params := ResolveParams{
Source: source,
Args: args,
Context: p.Context,
FieldInfo: fieldInfo,
Params: p,
}
argsCall := []reflect.Value{}
var contextCall reflect.Value
if query.Context != nil {
contextCall = getContextForResolve(p.Context, query.Context)
} else {
contextCall = reflect.ValueOf(p.Context)
}
for i := 0; i < len(query.Args); i++ {
switch query.Args[i] {
case ArgTypeSource:
argsCall = append(argsCall, reflect.ValueOf(source))
break
case ArgTypeArgs:
if args == nil {
argsCall = append(argsCall, reflect.ValueOf(map[string]interface{}{}))
} else {
argsCall = append(argsCall, reflect.ValueOf(args))
}
break
case ArgTypeContext:
argsCall = append(argsCall, contextCall)
break
case ArgTypeParams:
argsCall = append(argsCall, reflect.ValueOf(params))
break
}
}
handleValue := reflect.ValueOf(query.Handle)
resValue := handleValue.Call(argsCall)
if resValue[1].Interface() != nil {
return nil, resValue[1].Interface().(error)
}
return resValue[0].Interface(), nil
}
func MapToStruct(input interface{}, output interface{}) error {
b, err := json.Marshal(input)
if err != nil {
return err
}
err = json.Unmarshal(b, output)
if err != nil {
return err
}
return nil
}
func getArgsForResolve(args map[string]interface{}, typ reflect.Type) reflect.Value {
var output = reflect.New(typ)
for key, value := range args {
n := lU(key)
if _, ok := typ.FieldByName(n); ok {
field := output.Elem().FieldByName(n)
if field.CanInterface() {
if field.Kind() == reflect.Ptr {
v := reflect.ValueOf(value)
if v.Type().Kind() == reflect.Ptr {
field.Set(v)
} else {
field.Set(reflect.New(field.Type().Elem()))
field.Elem().Set(v)
}
} else {
field.Set(reflect.ValueOf(value))
}
}
}
}
return output.Elem()
}
func getContextForResolve(context context.Context, typ reflect.Type) reflect.Value {
var output = reflect.New(typ)
for i := 0; i < typ.NumField(); i++ {
if !output.Elem().Field(i).CanInterface() {
continue
}
value := context.Value(lA(typ.Field(i).Name))
if value == nil {
continue
}
output.Elem().Field(i).Set(reflect.ValueOf(value))
}
return output.Elem()
}
type UseFn func(params ResolveParams) (interface{}, bool, error)
func (r *Router) Use(fn UseFn) {
r.uses = append(r.uses, fn)
}
func (r *Router) Mutation(name string, handle interface{}) {
}
func (r *Router) UseResolve(name string, handle interface{}) {
r.resolves[name] = r.getRouteParams(handle)
}
func (r *Router) getRouteParams(handle interface{}) RouteParams {
handleType := reflect.TypeOf(handle)
if handleType.Kind() != reflect.Func {
panic("Invalid query handle, expected func, has " + handleType.Kind().String())
}
if handleType.NumOut() != 2 {
panic("Invalid query handle, func should return 2 parameters interface, error")
}
args := []int{}
current := 0
params := RouteParams{}
for i := 0; i < handleType.NumIn(); i++ {
if handleType.In(i) == reflect.TypeOf(ResolveParams{}) {
args = append(args, ArgTypeParams)
} else {
switch current {
case 0:
args = append(args, ArgTypeSource)
break
case 1:
args = append(args, ArgTypeArgs)
break
case 2:
params.Context = handleType.In(i)
args = append(args, ArgTypeContext)
break
}
current++
}
}
params.Handle = handle
params.Args = args
return params
}
func (r *Router) Query(path string, handle interface{}) {
r.queries[path] = r.getRouteParams(handle)
}
type RouterError struct {
Text string
}
type InvalidSourceError struct {
RouterError
}
type NotFoundRoute struct {
RouterError
}
func (e RouterError) Error() string {
return e.Text
}