2020-10-14 10:43:31 +00:00
|
|
|
package eventstore
|
|
|
|
|
2020-10-23 14:16:46 +00:00
|
|
|
import "time"
|
|
|
|
|
|
|
|
func NewReadModel(id string) *ReadModel {
|
|
|
|
return &ReadModel{
|
|
|
|
ID: id,
|
|
|
|
Events: []Event{},
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-10-14 10:43:31 +00:00
|
|
|
//ReadModel is the minimum representation of a View model.
|
|
|
|
// it might be saved in a database or in memory
|
|
|
|
type ReadModel struct {
|
2020-10-23 14:16:46 +00:00
|
|
|
ProcessedSequence uint64 `json:"-"`
|
|
|
|
ID string `json:"-"`
|
|
|
|
CreationDate time.Time `json:"-"`
|
|
|
|
ChangeDate time.Time `json:"-"`
|
|
|
|
Events []Event `json:"-"`
|
2020-10-14 10:43:31 +00:00
|
|
|
}
|
|
|
|
|
2020-10-23 14:16:46 +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
|
2020-10-23 14:16:46 +00:00
|
|
|
func (rm *ReadModel) AppendEvents(events ...Event) *ReadModel {
|
|
|
|
rm.Events = append(rm.Events, events...)
|
|
|
|
return rm
|
|
|
|
}
|
|
|
|
|
|
|
|
//Reduce must be the last step in the reduce function of the extension
|
|
|
|
func (rm *ReadModel) Reduce() error {
|
|
|
|
if len(rm.Events) == 0 {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
if rm.CreationDate.IsZero() {
|
2020-11-06 12:47:27 +00:00
|
|
|
rm.CreationDate = rm.Events[0].Base().creationDate
|
2020-10-23 14:16:46 +00:00
|
|
|
}
|
2020-11-06 12:47:27 +00:00
|
|
|
rm.ChangeDate = rm.Events[len(rm.Events)-1].Base().creationDate
|
|
|
|
rm.ProcessedSequence = rm.Events[len(rm.Events)-1].Base().sequence
|
2020-10-23 14:16:46 +00:00
|
|
|
// all events processed and not needed anymore
|
|
|
|
rm.Events = nil
|
|
|
|
rm.Events = []Event{}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func NewAggregate(id string) *Aggregate {
|
|
|
|
return &Aggregate{
|
|
|
|
ID: id,
|
|
|
|
Events: []Event{},
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
type Aggregate struct {
|
|
|
|
PreviousSequence uint64 `json:"-"`
|
|
|
|
ID string `json:"-"`
|
|
|
|
Events []Event `json:"-"`
|
|
|
|
}
|
|
|
|
|
|
|
|
//AppendEvents adds all the events to the aggregate.
|
|
|
|
// The function doesn't compute the new state of the aggregate
|
|
|
|
func (a *Aggregate) AppendEvents(events ...Event) *Aggregate {
|
2020-10-14 10:43:31 +00:00
|
|
|
a.Events = append(a.Events, events...)
|
2020-10-23 14:16:46 +00:00
|
|
|
return a
|
|
|
|
}
|
|
|
|
|
|
|
|
//Reduce must be the last step in the reduce function of the extension
|
|
|
|
func (a *Aggregate) Reduce() error {
|
|
|
|
if len(a.Events) == 0 {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2020-11-06 12:47:27 +00:00
|
|
|
a.PreviousSequence = a.Events[len(a.Events)-1].Base().sequence
|
2020-10-23 14:16:46 +00:00
|
|
|
// all events processed and not needed anymore
|
|
|
|
a.Events = nil
|
|
|
|
a.Events = []Event{}
|
|
|
|
return nil
|
2020-10-14 10:43:31 +00:00
|
|
|
}
|