forked from chiguirez/cromberbus
-
Notifications
You must be signed in to change notification settings - Fork 0
/
command_middleware.go
55 lines (41 loc) · 1.19 KB
/
command_middleware.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
package cromberbus
type CommandCallable func(command Command) error
type Middleware interface {
Execute(command Command, next CommandCallable) error
}
type commandHandlingMiddleware struct {
handlerResolver CommandHandlerResolver
}
func (m commandHandlingMiddleware) Execute(command Command, next CommandCallable) error {
handler, err := m.handlerResolver.Resolve(command)
if err != nil {
return err
}
if err := handler.Call(command); err != nil {
return err
}
return next(command)
}
type MiddlewareList []Middleware
func NewMiddlewareList(commandHandler Middleware) MiddlewareList {
return []Middleware{commandHandler}
}
func (m MiddlewareList) Queue(middleware ...Middleware) MiddlewareList {
return append(m, middleware...)
}
func (m MiddlewareList) start(command Command) error {
return m.getCallable(0)(command)
}
func (m MiddlewareList) lastIndex() int {
return len(m) - 1
}
func (m MiddlewareList) getCallable(index int) CommandCallable {
lastCallable := func(command Command) error { return nil }
if index > m.lastIndex() {
return lastCallable
}
return func(command Command) error {
middleware := m[index]
return middleware.Execute(command, m.getCallable(index+1))
}
}