-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbind.go
More file actions
88 lines (70 loc) · 2.06 KB
/
bind.go
File metadata and controls
88 lines (70 loc) · 2.06 KB
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
package needle
import (
"context"
"github.com/danpasecinic/needle/internal/container"
"github.com/danpasecinic/needle/internal/reflect"
)
type Decorator[T any] func(ctx context.Context, r Resolver, base T) (T, error)
func Bind[I, T any](c *Container, opts ...ProviderOption) error {
cfg := &providerConfig{}
for _, opt := range opts {
opt(cfg)
}
interfaceKey := reflect.TypeKey[I]()
implKey := reflect.TypeKey[T]()
if cfg.name != "" {
interfaceKey = reflect.TypeKeyNamed[I](cfg.name)
}
wrappedProvider := func(ctx context.Context, r container.Resolver) (any, error) {
return r.Resolve(ctx, implKey)
}
if err := c.internal.Register(interfaceKey, wrappedProvider, []string{implKey}); err != nil {
return err
}
for _, hook := range cfg.onStart {
c.internal.AddOnStart(interfaceKey, hook)
}
for _, hook := range cfg.onStop {
c.internal.AddOnStop(interfaceKey, hook)
}
return nil
}
func BindNamed[I, T any](c *Container, name string, opts ...ProviderOption) error {
opts = append(opts, WithName(name))
return Bind[I, T](c, opts...)
}
func Decorate[T any](c *Container, decorator Decorator[T]) {
key := reflect.TypeKey[T]()
c.internal.AddDecorator(
key, func(ctx context.Context, r container.Resolver, instance any) (any, error) {
typed, ok := instance.(T)
if !ok {
var zero T
return zero, errDecoratorTypeMismatch(reflect.TypeName[T]())
}
resolver := &resolverAdapter{container: c}
return decorator(ctx, resolver, typed)
},
)
}
func DecorateNamed[T any](c *Container, name string, decorator Decorator[T]) {
key := reflect.TypeKeyNamed[T](name)
c.internal.AddDecorator(
key, func(ctx context.Context, r container.Resolver, instance any) (any, error) {
typed, ok := instance.(T)
if !ok {
var zero T
return zero, errDecoratorTypeMismatch(reflect.TypeName[T]())
}
resolver := &resolverAdapter{container: c}
return decorator(ctx, resolver, typed)
},
)
}
func errDecoratorTypeMismatch(typeName string) *Error {
return newError(
ErrCodeDecoratorFailed,
"decorator type mismatch for "+typeName,
nil,
)
}