-
Notifications
You must be signed in to change notification settings - Fork 0
/
command_bus.go
83 lines (67 loc) · 1.75 KB
/
command_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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
package commandbus
import (
"reflect"
"sort"
"sync"
)
type HandlerFunc func(cmd interface{})
type middlewareFunc func(cmd interface{}, next HandlerFunc)
type middleware struct {
function middlewareFunc
priority int
}
type byPriority []middleware
func (slice byPriority) Len() int {
return len(slice)
}
func (slice byPriority) Less(i, j int) bool {
return slice[i].priority > slice[j].priority
}
func (slice byPriority) Swap(i, j int) {
slice[i], slice[j] = slice[j], slice[i]
}
type CommandBus struct {
handlers map[reflect.Type]HandlerFunc
middlewares []middleware
lock sync.Mutex
}
func (bus *CommandBus) RegisterHandler(cmd interface{}, handler HandlerFunc) {
bus.lock.Lock()
defer bus.lock.Unlock()
bus.handlers[reflect.TypeOf(cmd)] = handler
}
func (bus *CommandBus) AddMiddleware(priority int, function middlewareFunc) {
bus.lock.Lock()
defer bus.lock.Unlock()
bus.middlewares = append(bus.middlewares, middleware{function: function, priority: priority})
sort.Sort(byPriority(bus.middlewares))
}
func (bus CommandBus) Handle(cmd interface{}) {
bus.lock.Lock()
defer bus.lock.Unlock()
handler := bus.getNext(0)
handler(cmd)
}
func (bus CommandBus) getNext(index int) HandlerFunc {
if len(bus.middlewares) >= (index + 1) {
return func(cmd interface{}) {
middleware := bus.middlewares[index]
middleware.function(cmd, bus.getNext(index+1))
}
}
return func(cmd interface{}) {
if handler := bus.GetHandler(cmd); handler != nil {
handler(cmd)
}
}
}
func (bus CommandBus) GetHandler(cmd interface{}) HandlerFunc {
handler, _ := bus.handlers[reflect.TypeOf(cmd)]
return handler
}
func New() *CommandBus {
return &CommandBus{
handlers: make(map[reflect.Type]HandlerFunc),
middlewares: make([]middleware, 0),
}
}