2021-01-04 14:52:13 +01:00
|
|
|
package query
|
2020-11-11 17:51:44 +01:00
|
|
|
|
|
|
|
import (
|
2021-02-23 15:13:04 +01:00
|
|
|
"github.com/caos/zitadel/internal/eventstore"
|
|
|
|
"github.com/caos/zitadel/internal/repository/member"
|
2020-11-11 17:51:44 +01:00
|
|
|
)
|
|
|
|
|
2021-01-04 14:52:13 +01:00
|
|
|
type MembersReadModel struct {
|
2020-11-11 17:51:44 +01:00
|
|
|
eventstore.ReadModel
|
|
|
|
|
2021-01-04 14:52:13 +01:00
|
|
|
Members []*MemberReadModel
|
2020-11-11 17:51:44 +01:00
|
|
|
}
|
|
|
|
|
2021-01-04 14:52:13 +01:00
|
|
|
func (rm *MembersReadModel) MemberByUserID(id string) (idx int, member *MemberReadModel) {
|
2020-11-11 17:51:44 +01:00
|
|
|
for idx, member = range rm.Members {
|
|
|
|
if member.UserID == id {
|
|
|
|
return idx, member
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return -1, nil
|
|
|
|
}
|
|
|
|
|
2021-01-04 14:52:13 +01:00
|
|
|
func (rm *MembersReadModel) AppendEvents(events ...eventstore.EventReader) {
|
2020-11-11 17:51:44 +01:00
|
|
|
for _, event := range events {
|
|
|
|
switch e := event.(type) {
|
2021-01-04 14:52:13 +01:00
|
|
|
case *member.MemberAddedEvent:
|
|
|
|
m := NewMemberReadModel(e.UserID)
|
2020-11-26 09:19:14 +01:00
|
|
|
rm.Members = append(rm.Members, m)
|
|
|
|
m.AppendEvents(e)
|
2021-01-04 14:52:13 +01:00
|
|
|
case *member.MemberChangedEvent:
|
2020-11-26 09:19:14 +01:00
|
|
|
_, m := rm.MemberByUserID(e.UserID)
|
|
|
|
m.AppendEvents(e)
|
2021-01-04 14:52:13 +01:00
|
|
|
case *member.MemberRemovedEvent:
|
2020-11-11 17:51:44 +01:00
|
|
|
idx, _ := rm.MemberByUserID(e.UserID)
|
|
|
|
if idx < 0 {
|
2020-11-25 14:12:44 +01:00
|
|
|
continue
|
2020-11-11 17:51:44 +01:00
|
|
|
}
|
|
|
|
copy(rm.Members[idx:], rm.Members[idx+1:])
|
|
|
|
rm.Members[len(rm.Members)-1] = nil
|
|
|
|
rm.Members = rm.Members[:len(rm.Members)-1]
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-01-04 14:52:13 +01:00
|
|
|
func (rm *MembersReadModel) Reduce() (err error) {
|
2020-11-26 09:19:14 +01:00
|
|
|
for _, m := range rm.Members {
|
|
|
|
err = m.Reduce()
|
2020-11-11 17:51:44 +01:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return rm.ReadModel.Reduce()
|
|
|
|
}
|