-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcontext.go
74 lines (64 loc) · 1.58 KB
/
context.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
package materialize
import (
"fmt"
"reflect"
)
// Context is a materialize context, which passed to factory as first argument.
type Context struct {
m *Materializer
p *Context
f *Factory
val interface{}
err error
}
func (x *Context) child(f *Factory) *Context {
return &Context{
m: x.m,
p: x,
f: f,
}
}
// Error returns last happened error if available.
func (x *Context) Error() error {
return x.err
}
// Resolve resolves an instance temporary. This cuts circular references.
func (x *Context) Resolve(v interface{}) *Context {
if x.val != nil {
panic(fmt.Sprintf("have resolved already %s", x.f.Type))
}
typ := reflect.TypeOf(v)
if typ != x.f.Type {
panic(fmt.Sprintf("unmatched type, required type is %s", x.f.Type))
}
x.val = v
return x
}
// Materialize materializes an instance with tags.
func (x *Context) Materialize(receiver interface{}, queryTags ...string) *Context {
if x.err != nil {
return x
}
x.err = x.m.materialize(x, receiver, queryTags)
return x
}
// Option materializes an optional instance with tags.
// The error happened are not stored to Context.
func (x *Context) Option(receiver interface{}, queryTags ...string) error {
return x.m.materialize(x, receiver, queryTags)
}
func (x *Context) getObj(f *Factory) (reflect.Value, bool, error) {
for x != nil {
if x.f == f {
if x.val == nil {
return reflect.Value{}, false, fmt.Errorf("not resolved *materialize.Context for %s", x.f.Type)
}
return reflect.ValueOf(x.val), true, nil
}
x = x.p
}
return reflect.Value{}, false, nil
}
func (x *Context) typ() reflect.Type {
return x.f.Type
}