-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcallback.go
More file actions
96 lines (92 loc) · 2.32 KB
/
callback.go
File metadata and controls
96 lines (92 loc) · 2.32 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
89
90
91
92
93
94
95
96
package figtree
import (
"errors"
)
// WithCallback allows you to assign a slice of CallbackFunc to a figFruit attached to a figTree.
// A callback is executed when the value of the configurable CHANGES
//
// Example:
//
// figs := With(Options{Pollinate: true, Tracking, true, Harvest: 1776})
// figs.NewString("domain", "", "domain name")
// figs.WithCallback("domain", figtree.CallbackAfterVerify, func(value interface{}) error {
// var sv string
// switch v := value.(type) {
// case *string:
// sv = *v
// case string:
// sv = v
// default:
// return fmt.Errorf("invalid type want %T, got %T", sv, v)
// }
// // do something with the sv domain after its been verified
// })
func (tree *figTree) WithCallback(name string, whenCallback CallbackWhen, runThis CallbackFunc) Plant {
tree.mu.Lock()
defer tree.mu.Unlock()
name = tree.resolveName(name)
fruit, exists := tree.figs[name]
if !exists || fruit == nil {
return tree
}
if fruit.HasRule(RuleNoCallbacks) {
return tree
}
fruit.Callbacks = append(fruit.Callbacks, Callback{
CallbackWhen: whenCallback,
CallbackFunc: runThis,
})
tree.figs[name] = fruit
return tree
}
// runCallbacks inspects each fig fruit on the tree and executes runCallbacks() against the fig fruit
func (tree *figTree) runCallbacks(callbackOn CallbackWhen) error {
tree.mu.RLock()
defer tree.mu.RUnlock()
for _, fig := range tree.figs {
if len(fig.Callbacks) == 0 {
continue
}
if fig.HasRule(RuleNoCallbacks) {
continue
}
err := fig.runCallbacks(tree, callbackOn)
if err != nil {
return err
}
}
for _, fruit := range tree.figs {
if fruit.Error != nil {
return fruit.Error
}
}
return nil
}
// runCallbacks will take each registered callback and run it against the fig fruit
func (fig *figFruit) runCallbacks(tree *figTree, callbackOn CallbackWhen) error {
if fig.Error != nil {
return fig.Error
}
if fig.HasRule(RuleNoCallbacks) {
return nil
}
errs := make([]error, len(fig.Callbacks))
for _, callback := range fig.Callbacks {
if callback.CallbackWhen == callbackOn {
value, err := tree.from(fig.name)
if err != nil {
errs = append(errs, err)
continue
}
err = callback.CallbackFunc(value.Value)
if err != nil {
errs = append(errs, err)
continue
}
}
}
if len(errs) > 0 {
return errors.Join(errs...)
}
return nil
}