zitadel/internal/query/members_model.go

54 lines
1.2 KiB
Go
Raw Normal View History

package query
2020-11-11 17:51:44 +01:00
import (
"github.com/caos/zitadel/internal/eventstore"
"github.com/caos/zitadel/internal/repository/member"
2020-11-11 17:51:44 +01:00
)
type MembersReadModel struct {
2020-11-11 17:51:44 +01:00
eventstore.ReadModel
Members []*MemberReadModel
2020-11-11 17:51:44 +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
}
func (rm *MembersReadModel) AppendEvents(events ...eventstore.EventReader) {
2020-11-11 17:51:44 +01:00
for _, event := range events {
switch e := event.(type) {
case *member.MemberAddedEvent:
m := NewMemberReadModel(e.UserID)
2020-11-26 09:19:14 +01:00
rm.Members = append(rm.Members, m)
m.AppendEvents(e)
case *member.MemberChangedEvent:
2020-11-26 09:19:14 +01:00
_, m := rm.MemberByUserID(e.UserID)
m.AppendEvents(e)
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]
}
}
}
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()
}