-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathcommandbus.go
42 lines (32 loc) · 907 Bytes
/
commandbus.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
package cromberbus
import (
"context"
"github.com/chiguirez/cromberbus/v3/commandhandler"
"github.com/chiguirez/cromberbus/v3/maphandler"
"github.com/chiguirez/cromberbus/v3/middleware"
)
type Command interface{}
type CommandBus struct {
middlewareList middleware.List
resolver maphandler.Resolver
}
func (c *CommandBus) Use(middleware middleware.Handler) {
c.middlewareList.Add(middleware)
}
func (c CommandBus) Dispatch(ctx context.Context, command Command) error {
cHandler, err := c.resolver.Resolve(command)
if err != nil {
return err
}
return c.middlewareList.BuildWith(middleware.Wrap(cHandler)).Call(ctx, command)
}
func New(handlers ...commandhandler.Class) CommandBus {
resolver := maphandler.NewResolver()
for _, h := range handlers {
resolver.AddHandler(h)
}
return CommandBus{
middlewareList: make([]middleware.Handler, 0),
resolver: resolver,
}
}