forked from mishudark/eventhus
-
Notifications
You must be signed in to change notification settings - Fork 0
/
command_handler.go
56 lines (47 loc) · 1.28 KB
/
command_handler.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
package eventhus
import (
"fmt"
"reflect"
"sync"
)
// CommandHandle defines the contract to handle commands
type CommandHandle interface {
Handle(command Command) error
}
// CommandHandlerRegister stores the handlers for commands
type CommandHandlerRegister interface {
Add(command interface{}, handler CommandHandle)
Get(command interface{}) (CommandHandle, error)
// Handlers() []string
}
// CommandRegister contains a registry of command-handler style
type CommandRegister struct {
sync.RWMutex
registry map[string]CommandHandle
// repository *Repository
}
// NewCommandRegister creates a new CommandHandler
func NewCommandRegister() *CommandRegister {
return &CommandRegister{
registry: make(map[string]CommandHandle),
// repository: repository,
}
}
// Add a new command with its handler
func (c *CommandRegister) Add(command interface{}, handler CommandHandle) {
c.Lock()
defer c.Unlock()
rawType := reflect.TypeOf(command)
name := rawType.String()
c.registry[name] = handler
}
// Get the handler for a command
func (c *CommandRegister) Get(command interface{}) (CommandHandle, error) {
rawType := reflect.TypeOf(command)
name := rawType.String()
handler, ok := c.registry[name]
if !ok {
return nil, fmt.Errorf("can't find %s in registry", name)
}
return handler, nil
}