Repository navigation
Expand file tree
/
Copy pathentity.go
More file actions
76 lines (68 loc) · 1.81 KB
/
Copy pathentity.go
File metadata and controls
76 lines (68 loc) · 1.81 KB
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
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) {
return NewEntityWithStringType(id, "", eventsSlice)
}
// NewEntityWithStringType instantiates a new T with the given
// stream type and events applied to it.
// At the same time the entity's internal Stream is initialised,
// so it can record new upcoming stream.
func NewEntityWithStringType[T Entity[T]](
id string,
streamType string,
eventsSlice []VersionedEvent[T],
) (*T, error) {
var t T
stream, err := newStream(
id,
streamType,
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
}