2020-10-14 10:43:31 +00:00
|
|
|
package eventstore
|
|
|
|
|
2024-09-24 16:43:29 +00:00
|
|
|
import "time"
|
2020-10-23 14:16:46 +00:00
|
|
|
|
2023-02-27 21:36:43 +00:00
|
|
|
// ReadModel is the minimum representation of a read model.
|
2020-11-11 16:51:44 +00:00
|
|
|
// It implements a basic reducer
|
2020-10-14 10:43:31 +00:00
|
|
|
// it might be saved in a database or in memory
|
|
|
|
type ReadModel struct {
|
2024-09-24 16:43:29 +00:00
|
|
|
AggregateID string `json:"-"`
|
|
|
|
ProcessedSequence uint64 `json:"-"`
|
|
|
|
CreationDate time.Time `json:"-"`
|
|
|
|
ChangeDate time.Time `json:"-"`
|
|
|
|
Events []Event `json:"-"`
|
|
|
|
ResourceOwner string `json:"-"`
|
|
|
|
InstanceID string `json:"-"`
|
|
|
|
Position float64 `json:"-"`
|
2020-10-14 10:43:31 +00:00
|
|
|
}
|
|
|
|
|
2023-02-27 21:36:43 +00:00
|
|
|
// AppendEvents adds all the events to the read model.
|
2020-10-14 10:43:31 +00:00
|
|
|
// The function doesn't compute the new state of the read model
|
2023-02-27 21:36:43 +00:00
|
|
|
func (rm *ReadModel) AppendEvents(events ...Event) {
|
2020-10-23 14:16:46 +00:00
|
|
|
rm.Events = append(rm.Events, events...)
|
|
|
|
}
|
|
|
|
|
2023-02-27 21:36:43 +00:00
|
|
|
// Reduce is the basic implementation of reducer
|
2020-11-11 16:51:44 +00:00
|
|
|
// If this function is extended the extending function should be the last step
|
2020-10-23 14:16:46 +00:00
|
|
|
func (rm *ReadModel) Reduce() error {
|
|
|
|
if len(rm.Events) == 0 {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2020-11-11 16:51:44 +00:00
|
|
|
if rm.AggregateID == "" {
|
2021-02-18 13:48:27 +00:00
|
|
|
rm.AggregateID = rm.Events[0].Aggregate().ID
|
2020-11-11 16:51:44 +00:00
|
|
|
}
|
2020-11-12 21:50:01 +00:00
|
|
|
if rm.ResourceOwner == "" {
|
2021-02-18 13:48:27 +00:00
|
|
|
rm.ResourceOwner = rm.Events[0].Aggregate().ResourceOwner
|
2020-11-12 21:50:01 +00:00
|
|
|
}
|
2022-03-23 08:02:39 +00:00
|
|
|
if rm.InstanceID == "" {
|
|
|
|
rm.InstanceID = rm.Events[0].Aggregate().InstanceID
|
2022-03-15 06:19:02 +00:00
|
|
|
}
|
2020-11-11 16:51:44 +00:00
|
|
|
|
2020-10-23 14:16:46 +00:00
|
|
|
if rm.CreationDate.IsZero() {
|
2023-10-19 10:19:10 +00:00
|
|
|
rm.CreationDate = rm.Events[0].CreatedAt()
|
2020-10-23 14:16:46 +00:00
|
|
|
}
|
2023-10-19 10:19:10 +00:00
|
|
|
rm.ChangeDate = rm.Events[len(rm.Events)-1].CreatedAt()
|
2020-11-06 16:25:07 +00:00
|
|
|
rm.ProcessedSequence = rm.Events[len(rm.Events)-1].Sequence()
|
2024-06-12 09:11:36 +00:00
|
|
|
rm.Position = rm.Events[len(rm.Events)-1].Position()
|
2020-10-23 14:16:46 +00:00
|
|
|
// all events processed and not needed anymore
|
2024-02-28 08:55:54 +00:00
|
|
|
rm.Events = rm.Events[0:0]
|
2020-10-23 14:16:46 +00:00
|
|
|
return nil
|
|
|
|
}
|