-
Notifications
You must be signed in to change notification settings - Fork 3
/
cqrs.go
73 lines (61 loc) · 1.33 KB
/
cqrs.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
package cqrs
import (
"encoding/json"
"reflect"
"time"
"github.com/satori/go.uuid"
)
func GenerateUUID() string {
return uuid.NewV4().String()
}
type Message struct {
Id string
Timestamp int64
Type string
Payload interface{}
}
type RawMessage struct {
Id string
Timestamp int64
Type string
Payload json.RawMessage
}
type AggregateRoot struct {
Changes map[string]Message
dispatcher Dispatcher
}
type Stringer interface {
String() string
}
func NewAggregateRoot(source interface{}) *AggregateRoot {
a := AggregateRoot{
make(map[string]Message),
Dispatcher{}}
a.dispatcher.RegisterHandlers(source)
return &a
}
func NewAggregateRootFromHistory(source interface{}, history []Message) *AggregateRoot {
a := NewAggregateRoot(source)
for _, event := range history {
a.dispatcher.Dispatch(event.Payload)
}
return a
}
func (a *AggregateRoot) ClearChanges() {
a.Changes = make(map[string]Message)
}
func NewMessage(originalEvent interface{}) Message {
eventType := reflect.TypeOf(originalEvent)
message := Message{
GenerateUUID(),
time.Now().Unix(),
eventType.Name(),
originalEvent}
return message
}
func (a *AggregateRoot) Source(originalEvent interface{}) error {
event := NewMessage(originalEvent)
a.dispatcher.Dispatch(originalEvent)
a.Changes[event.Id] = event
return nil
}