/
option.go
92 lines (74 loc) · 1.79 KB
/
option.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
package container
import (
"fmt"
"github.com/procyon-projects/reflector"
)
type Option func(def *Definition) error
func Name(name string) Option {
return func(def *Definition) error {
def.name = name
return nil
}
}
func Optional[T any]() Option {
return func(def *Definition) error {
typ := reflector.TypeOf[T]()
exists := false
for _, input := range def.inputs {
if input.Type().Compare(typ) {
input.optional = true
exists = true
}
}
if !exists {
return fmt.Errorf("container: could not find any input of type %s", typ.Name())
}
return nil
}
}
func OptionalAt(index int) Option {
return func(def *Definition) error {
if index < 0 {
panic(fmt.Sprintf("container: index should be greater than or equal to zero, but got index %d", index))
}
if len(def.inputs) <= index {
return fmt.Errorf("container: could not find any input at index %d", index)
}
def.inputs[index].optional = true
return nil
}
}
func Qualifier[T any](name string) Option {
return func(def *Definition) error {
typ := reflector.TypeOf[T]()
exists := false
for _, input := range def.inputs {
if input.Type().Compare(typ) {
input.name = name
exists = true
}
}
if !exists {
return fmt.Errorf("container: could not find any input of type %s", typ.Name())
}
return nil
}
}
func QualifierAt(index int, name string) Option {
return func(def *Definition) error {
if index < 0 {
panic(fmt.Sprintf("container: index should be greater than or equal to zero, but got index %d", index))
}
if len(def.inputs) <= index {
return fmt.Errorf("container: could not find any input at index %d", index)
}
def.inputs[index].name = name
return nil
}
}
func Scoped(scope string) Option {
return func(def *Definition) error {
def.scope = scope
return nil
}
}