2020-11-11 16:51:44 +00:00
|
|
|
package members
|
|
|
|
|
|
|
|
import (
|
|
|
|
"github.com/caos/zitadel/internal/eventstore/v2"
|
|
|
|
"github.com/caos/zitadel/internal/v2/repository/member"
|
|
|
|
)
|
|
|
|
|
|
|
|
type ReadModel struct {
|
|
|
|
eventstore.ReadModel
|
|
|
|
|
|
|
|
Members []*member.ReadModel
|
|
|
|
}
|
|
|
|
|
|
|
|
func (rm *ReadModel) MemberByUserID(id string) (idx int, member *member.ReadModel) {
|
|
|
|
for idx, member = range rm.Members {
|
|
|
|
if member.UserID == id {
|
|
|
|
return idx, member
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return -1, nil
|
|
|
|
}
|
|
|
|
|
2020-11-25 13:12:44 +00:00
|
|
|
func (rm *ReadModel) AppendEvents(events ...eventstore.EventReader) {
|
2020-11-11 16:51:44 +00:00
|
|
|
for _, event := range events {
|
|
|
|
switch e := event.(type) {
|
2020-11-12 21:50:01 +00:00
|
|
|
case *member.AddedEvent:
|
2020-11-30 05:40:56 +00:00
|
|
|
m := member.NewReadModel(e.UserID)
|
2020-11-26 08:19:14 +00:00
|
|
|
rm.Members = append(rm.Members, m)
|
|
|
|
m.AppendEvents(e)
|
2020-11-12 21:50:01 +00:00
|
|
|
case *member.ChangedEvent:
|
2020-11-26 08:19:14 +00:00
|
|
|
_, m := rm.MemberByUserID(e.UserID)
|
|
|
|
m.AppendEvents(e)
|
2020-11-12 21:50:01 +00:00
|
|
|
case *member.RemovedEvent:
|
2020-11-11 16:51:44 +00:00
|
|
|
idx, _ := rm.MemberByUserID(e.UserID)
|
|
|
|
if idx < 0 {
|
2020-11-25 13:12:44 +00:00
|
|
|
continue
|
2020-11-11 16:51:44 +00:00
|
|
|
}
|
|
|
|
copy(rm.Members[idx:], rm.Members[idx+1:])
|
|
|
|
rm.Members[len(rm.Members)-1] = nil
|
|
|
|
rm.Members = rm.Members[:len(rm.Members)-1]
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (rm *ReadModel) Reduce() (err error) {
|
2020-11-26 08:19:14 +00:00
|
|
|
for _, m := range rm.Members {
|
|
|
|
err = m.Reduce()
|
2020-11-11 16:51:44 +00:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return rm.ReadModel.Reduce()
|
|
|
|
}
|