2020-11-20 17:03:17 +01:00
|
|
|
package eventstore
|
|
|
|
|
2020-11-25 14:12:44 +01:00
|
|
|
import "time"
|
|
|
|
|
2023-10-19 12:19:10 +02:00
|
|
|
// WriteModel is the minimum representation of a command side write model.
|
2020-11-20 17:03:17 +01:00
|
|
|
// It implements a basic reducer
|
|
|
|
// it's purpose is to reduce events to create new ones
|
|
|
|
type WriteModel struct {
|
2022-01-03 09:19:07 +01:00
|
|
|
AggregateID string `json:"-"`
|
|
|
|
ProcessedSequence uint64 `json:"-"`
|
|
|
|
Events []Event `json:"-"`
|
|
|
|
ResourceOwner string `json:"-"`
|
2022-03-23 09:02:39 +01:00
|
|
|
InstanceID string `json:"-"`
|
2022-01-03 09:19:07 +01:00
|
|
|
ChangeDate time.Time `json:"-"`
|
2020-11-20 17:03:17 +01:00
|
|
|
}
|
|
|
|
|
2023-10-19 12:19:10 +02:00
|
|
|
// AppendEvents adds all the events to the read model.
|
2020-11-20 17:03:17 +01:00
|
|
|
// The function doesn't compute the new state of the read model
|
2022-01-03 09:19:07 +01:00
|
|
|
func (rm *WriteModel) AppendEvents(events ...Event) {
|
2020-11-20 17:03:17 +01:00
|
|
|
rm.Events = append(rm.Events, events...)
|
|
|
|
}
|
|
|
|
|
2023-10-19 12:19:10 +02:00
|
|
|
// Reduce is the basic implementation of reducer
|
2020-11-20 17:03:17 +01:00
|
|
|
// If this function is extended the extending function should be the last step
|
2020-11-23 11:36:58 +01:00
|
|
|
func (wm *WriteModel) Reduce() error {
|
|
|
|
if len(wm.Events) == 0 {
|
2020-11-20 17:03:17 +01:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2020-11-23 11:36:58 +01:00
|
|
|
if wm.AggregateID == "" {
|
2021-02-18 14:48:27 +01:00
|
|
|
wm.AggregateID = wm.Events[0].Aggregate().ID
|
2020-11-20 17:03:17 +01:00
|
|
|
}
|
2020-11-23 11:36:58 +01:00
|
|
|
if wm.ResourceOwner == "" {
|
2021-02-18 14:48:27 +01:00
|
|
|
wm.ResourceOwner = wm.Events[0].Aggregate().ResourceOwner
|
2020-11-20 17:03:17 +01:00
|
|
|
}
|
2022-03-23 09:02:39 +01:00
|
|
|
if wm.InstanceID == "" {
|
|
|
|
wm.InstanceID = wm.Events[0].Aggregate().InstanceID
|
2022-03-15 07:19:02 +01:00
|
|
|
}
|
2020-11-20 17:03:17 +01:00
|
|
|
|
2020-11-23 11:36:58 +01:00
|
|
|
wm.ProcessedSequence = wm.Events[len(wm.Events)-1].Sequence()
|
2023-10-19 12:19:10 +02:00
|
|
|
wm.ChangeDate = wm.Events[len(wm.Events)-1].CreatedAt()
|
2020-11-20 17:03:17 +01:00
|
|
|
|
|
|
|
// all events processed and not needed anymore
|
2020-11-23 11:36:58 +01:00
|
|
|
wm.Events = nil
|
2022-01-03 09:19:07 +01:00
|
|
|
wm.Events = []Event{}
|
2020-11-20 17:03:17 +01:00
|
|
|
return nil
|
|
|
|
}
|