-
Notifications
You must be signed in to change notification settings - Fork 0
/
bus.go
65 lines (50 loc) · 1.19 KB
/
bus.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
package hexago
import "reflect"
// CmdBus decouples Cmd from its execution, dependencies, side effects.
type CmdBus interface {
Handle(Cmd) (string, error)
}
type InMemoryBus struct {
cmd *CmdBag
events *EventBag
capturedEvents []*Event
}
// NewInMemoryBus creates a fresh bus without any captured events.
func NewInMemoryBus(cmd *CmdBag, events *EventBag) InMemoryBus {
return InMemoryBus{
cmd: cmd,
events: events,
capturedEvents: make([]*Event, 0),
}
}
func (i InMemoryBus) Handle(cmd Cmd) (string, error) {
hf, err := i.cmd.FactoryFor(cmd.Name)
if err != nil {
return "", err
}
h := hf()
res, err := h.Handle(cmd)
v, err := extractRepoField(reflect.ValueOf(h))
if err != nil {
return res, err
}
repo, ok := v.Interface().(Repo)
if ok {
for _, agg := range repo.Seen() {
for _, e := range agg.Pull() {
i.capturedEvents = append(i.capturedEvents, &e)
}
}
}
for len(i.capturedEvents) != 0 {
e := i.capturedEvents[0]
i.capturedEvents = i.capturedEvents[1:]
i.handleEvent(*e)
}
return res, nil
}
func (i InMemoryBus) handleEvent(e Event) {
for _, ef := range i.events.FactoryFor(e.Name) {
ef().Handle(e)
}
}