-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcommand.go
54 lines (43 loc) · 1.56 KB
/
command.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
// Package cqrs provides a simple implementation of the command query responsibility segregation pattern.
package cqrs
import (
"context"
"errors"
"fmt"
"sync"
)
// Payload is the command payload. It can be any type.
// It can be then deserialized to the desired type using the TryMapPayload function.
type Payload any
// Command is the command that is dispatched to the command handler.
type Command struct {
Key Key // Key is the unique identifier of the command.
Payload Payload // Payload is the command payload.
}
// CommandHandlerFunc is the function that handles the command.
type CommandHandlerFunc func(ctx context.Context, cmd Command) error
var (
// commandHandlers is a map of command keys to a slice of command handler functions.
commandHandlers = make(map[Key][]CommandHandlerFunc)
commandMutex sync.Mutex
)
// RegisterCommandHandlerFuncs registers the given command handler functions for the given command key.
func RegisterCommandHandlerFuncs(cmdKey Key, h ...CommandHandlerFunc) {
commandMutex.Lock()
defer commandMutex.Unlock()
commandHandlers[cmdKey] = append(commandHandlers[cmdKey], h...)
}
var ErrCommandHandlerFuncNotFound = errors.New("command handler func for given command not found")
// DispatchCommand dispatches the given command to the command handler.
func DispatchCommand(ctx context.Context, cmd Command) error {
v, ok := commandHandlers[cmd.Key]
if !ok {
return fmt.Errorf("%w; %s", ErrCommandHandlerFuncNotFound, cmd.Key)
}
for _, h := range v {
if err := h(ctx, cmd); err != nil {
return err
}
}
return nil
}