2021-01-04 13:52:13 +00:00
|
|
|
package query
|
2020-11-11 16:51:44 +00:00
|
|
|
|
|
|
|
import (
|
2021-02-23 14:13:04 +00:00
|
|
|
"github.com/caos/zitadel/internal/eventstore"
|
|
|
|
"github.com/caos/zitadel/internal/repository/member"
|
2020-11-11 16:51:44 +00:00
|
|
|
)
|
|
|
|
|
2021-01-04 13:52:13 +00:00
|
|
|
type MembersReadModel struct {
|
2020-11-11 16:51:44 +00:00
|
|
|
eventstore.ReadModel
|
|
|
|
|
2021-01-04 13:52:13 +00:00
|
|
|
Members []*MemberReadModel
|
2020-11-11 16:51:44 +00:00
|
|
|
}
|
|
|
|
|
2021-01-04 13:52:13 +00:00
|
|
|
func (rm *MembersReadModel) MemberByUserID(id string) (idx int, member *MemberReadModel) {
|
2020-11-11 16:51:44 +00:00
|
|
|
for idx, member = range rm.Members {
|
|
|
|
if member.UserID == id {
|
|
|
|
return idx, member
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return -1, nil
|
|
|
|
}
|
|
|
|
|
2021-01-04 13:52:13 +00:00
|
|
|
func (rm *MembersReadModel) AppendEvents(events ...eventstore.EventReader) {
|
2020-11-11 16:51:44 +00:00
|
|
|
for _, event := range events {
|
|
|
|
switch e := event.(type) {
|
2021-01-04 13:52:13 +00:00
|
|
|
case *member.MemberAddedEvent:
|
|
|
|
m := NewMemberReadModel(e.UserID)
|
2020-11-26 08:19:14 +00:00
|
|
|
rm.Members = append(rm.Members, m)
|
|
|
|
m.AppendEvents(e)
|
2021-01-04 13:52:13 +00:00
|
|
|
case *member.MemberChangedEvent:
|
2020-11-26 08:19:14 +00:00
|
|
|
_, m := rm.MemberByUserID(e.UserID)
|
|
|
|
m.AppendEvents(e)
|
2021-01-04 13:52:13 +00:00
|
|
|
case *member.MemberRemovedEvent:
|
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]
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-01-04 13:52:13 +00:00
|
|
|
func (rm *MembersReadModel) 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()
|
|
|
|
}
|