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