forked from mishudark/eventhus
-
Notifications
You must be signed in to change notification settings - Fork 0
/
event.go
109 lines (88 loc) · 2.21 KB
/
event.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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
package eventhus
import (
"fmt"
"reflect"
"strings"
"sync"
)
var (
mu sync.RWMutex
registry = make(map[string]reflect.Type)
)
// Event stores the data for every event
type Event struct {
ID string `json:"id"`
AggregateID string `json:"aggregate_id"`
AggregateType string `json:"aggregate_type"`
Version int `json:"version"`
Type string `json:"type"`
Data interface{} `json:"data"`
}
// Register defines generic methods to create a registry
type Register interface {
Set(source interface{})
Get(name string) (interface{}, error)
Count() int
}
// EventTypeRegister defines the register for all the events that are Data field child of event struct
type EventTypeRegister interface {
Register
Events() []string
}
// EventType implements the EventyTypeRegister interface
type EventType struct {
sync.RWMutex
}
// NewEventRegister gets a EventyTypeRegister interface
func NewEventRegister() EventTypeRegister {
return &EventType{}
}
// Set a new type
func (e *EventType) Set(source interface{}) {
rawType, name := GetTypeName(source)
mu.Lock()
registry[name] = rawType
mu.Unlock()
}
// Get a type based on its name
func (e *EventType) Get(name string) (interface{}, error) {
mu.RLock()
rawType, ok := registry[name]
mu.RUnlock()
if !ok {
return nil, fmt.Errorf("can't find %s in registry", name)
}
return reflect.New(rawType).Interface(), nil
}
// Count the quantity of events registered
func (e *EventType) Count() int {
mu.RLock()
count := len(registry)
mu.RUnlock()
return count
}
// Events registered
func (e *EventType) Events() []string {
var i int
values := make([]string, len(registry))
mu.RLock()
for key := range registry {
values[i] = key
i++
}
mu.RUnlock()
return values
}
// GetTypeName of given struct
func GetTypeName(source interface{}) (reflect.Type, string) {
rawType := reflect.TypeOf(source)
// source is a pointer, convert to its value
if rawType.Kind() == reflect.Ptr {
rawType = rawType.Elem()
}
name := rawType.String()
// we need to extract only the name without the package
// name currently follows the format `package.StructName`
parts := strings.Split(name, ".")
return rawType, parts[1]
}