-
Notifications
You must be signed in to change notification settings - Fork 4
/
entity.go
57 lines (50 loc) · 1.41 KB
/
entity.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
package esja
// Entity represents the event-sourced type saved and loaded by the event store.
// In DDD terms, it is the "aggregate root".
//
// In order for your domain type to implement Entity:
// - Keep *Stream in a field.
// - Implement the interface methods in accordance with its description.
//
// Then an EventStore will be able to store and load it.
//
// Example:
//
// type User struct {
// stream *esja.Stream[User]
// id string
// }
//
// func (u User) Stream() *esja.Stream[User] {
// return u.stream
// }
//
// func (u User) NewWithStream(stream *esja.Stream[User]) *User {
// return &User{stream: stream}
// }
type Entity[T any] interface {
// Stream exposes a pointer to the internal entity's Stream.
Stream() *Stream[T]
// NewWithStream returns a new instance of T
// with the provided Stream queue injected.
NewWithStream(*Stream[T]) *T
}
// NewEntity instantiates a new T with the given events applied to it.
// At the same time the entity's internal Stream is initialised,
// so it can record new upcoming stream.
func NewEntity[T Entity[T]](id string, eventsSlice []VersionedEvent[T]) (*T, error) {
var t T
stream, err := newStream(id, eventsSlice)
if err != nil {
return nil, err
}
eventsSlice = stream.PopEvents()
target := t.NewWithStream(stream)
for _, e := range eventsSlice {
err := e.ApplyTo(target)
if err != nil {
return nil, err
}
}
return target, nil
}