forked from sbstjn/appsync-resolvers
-
Notifications
You must be signed in to change notification settings - Fork 1
/
resolver.go
57 lines (44 loc) · 1.08 KB
/
resolver.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
package resolvers
import (
"context"
"encoding/json"
"reflect"
)
type resolver struct {
function interface{}
}
func (r *resolver) hasContext() bool {
return reflect.TypeOf(r.function).NumIn() == 2
}
func (r *resolver) hasPayload() bool {
return reflect.TypeOf(r.function).NumIn() > 0
}
func (r *resolver) call(ctx context.Context, p json.RawMessage) (interface{}, error) {
args := make([]reflect.Value, 0, 2)
hasContext := r.hasContext()
if hasContext {
args = append(args, reflect.ValueOf(ctx))
}
if r.hasPayload() {
var index int
if hasContext {
index = 1
}
pld := payload{p}
val, err := pld.parse(reflect.TypeOf(r.function).In(index))
if err != nil {
return nil, err
}
args = append(args, val)
}
returnValues := reflect.ValueOf(r.function).Call(args)
var returnData interface{}
var returnError error
if len(returnValues) == 2 {
returnData = returnValues[0].Interface()
}
if err := returnValues[len(returnValues)-1].Interface(); err != nil {
returnError = returnValues[len(returnValues)-1].Interface().(error)
}
return returnData, returnError
}