-
Notifications
You must be signed in to change notification settings - Fork 0
/
dependency.go
73 lines (60 loc) · 1.75 KB
/
dependency.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
package go_remote
import (
"context"
"errors"
"reflect"
)
type dataRecord struct {
isConstant bool
rtype reflect.Type
value interface{}
}
type DependencyProvider func(ctx context.Context) interface{}
type dependencyStore struct {
data map[reflect.Type]reflect.Value
}
var errorInterface = reflect.TypeOf((*error)(nil)).Elem()
var contextInterface = reflect.TypeOf((*context.Context)(nil)).Elem()
func newDependencyStore() *dependencyStore {
return &dependencyStore{data: make(map[reflect.Type]reflect.Value)}
}
func (d *dependencyStore) AddProvider(provider interface{}) error {
pType := reflect.TypeOf(provider)
if pType.NumIn() != 1 || !pType.In(0).Implements(contextInterface) {
msg := "invalid data provider, provider must have a context as incoming parameter"
log.Errorf(msg)
return errors.New(msg)
}
if pType.NumOut() != 1 && (pType.NumOut() != 2 || pType.Out(1).Implements(errorInterface)) {
msg := "invalid data provider, provider must return a value and optional error"
log.Errorf(msg)
return errors.New(msg)
}
retType := pType.Out(0)
if retType.Kind() == reflect.Ptr {
retType = retType.Elem()
}
d.data[retType] = reflect.ValueOf(provider)
return nil
}
func (d *dependencyStore) Value(rtype reflect.Type, ctx context.Context) (reflect.Value, bool, error) {
keyType := rtype
if rtype.Kind() == reflect.Ptr {
keyType = rtype.Elem()
}
test, ok := d.data[keyType]
if !ok {
return reflect.Value{}, false, nil
}
var args []reflect.Value
args = []reflect.Value{reflect.ValueOf(ctx)}
out := test.Call(args)
if len(out) > 1 {
err, _ := out[1].Interface().(error)
if err != nil {
log.Errorf("error during calculation %s\n%s", rtype.Name(), err.Error())
}
return out[0], true, err
}
return out[0], true, nil
}