lab1
This commit is contained in:
@@ -0,0 +1,95 @@
|
||||
package memory
|
||||
|
||||
import (
|
||||
"context"
|
||||
"slices"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"mtusi-messenger/internal/domain"
|
||||
)
|
||||
|
||||
type ChatRepository struct {
|
||||
store *Store
|
||||
}
|
||||
|
||||
func (r *ChatRepository) Create(_ context.Context, draft domain.ChatDraft) (domain.Chat, error) {
|
||||
s := r.store
|
||||
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
|
||||
for _, id := range draft.MemberIDs {
|
||||
if _, ok := s.usersByID[id]; !ok {
|
||||
return domain.Chat{}, domain.ErrUnknownMember
|
||||
}
|
||||
}
|
||||
|
||||
chat := domain.Chat{
|
||||
ID: s.ids.NewID(),
|
||||
Title: draft.Title,
|
||||
MemberIDs: slices.Clone(draft.MemberIDs),
|
||||
CreatedAt: s.clock.Now(),
|
||||
}
|
||||
|
||||
s.chatsByID[chat.ID] = chat
|
||||
|
||||
at, _ := slices.BinarySearchFunc(s.chatsOrdered, chat, func(a, b domain.Chat) int {
|
||||
return compareKeyset(a.CreatedAt, a.ID, b.CreatedAt, b.ID)
|
||||
})
|
||||
s.chatsOrdered = slices.Insert(s.chatsOrdered, at, chat)
|
||||
|
||||
return cloneChat(chat), nil
|
||||
}
|
||||
|
||||
func (r *ChatRepository) GetVisible(_ context.Context, chatID, callerID uuid.UUID) (domain.Chat, error) {
|
||||
s := r.store
|
||||
|
||||
s.mu.RLock()
|
||||
defer s.mu.RUnlock()
|
||||
|
||||
chat, ok := s.chatsByID[chatID]
|
||||
if !ok || !chat.HasMember(callerID) {
|
||||
return domain.Chat{}, domain.ErrNotFound
|
||||
}
|
||||
|
||||
return cloneChat(chat), nil
|
||||
}
|
||||
|
||||
func (r *ChatRepository) ListVisible(
|
||||
_ context.Context,
|
||||
callerID uuid.UUID,
|
||||
after *domain.Cursor,
|
||||
limit int,
|
||||
) (domain.Page[domain.Chat], error) {
|
||||
s := r.store
|
||||
|
||||
s.mu.RLock()
|
||||
defer s.mu.RUnlock()
|
||||
|
||||
visible := make([]domain.Chat, 0, len(s.chatsOrdered))
|
||||
|
||||
for _, chat := range s.chatsOrdered {
|
||||
if chat.HasMember(callerID) {
|
||||
visible = append(visible, chat)
|
||||
}
|
||||
}
|
||||
|
||||
page := paginate(visible, callerID, chatKey, after, limit)
|
||||
for i, chat := range page.Items {
|
||||
page.Items[i] = cloneChat(chat)
|
||||
}
|
||||
|
||||
return page, nil
|
||||
}
|
||||
|
||||
func chatKey(chat domain.Chat) (time.Time, uuid.UUID) {
|
||||
return chat.CreatedAt, chat.ID
|
||||
}
|
||||
|
||||
func cloneChat(chat domain.Chat) domain.Chat {
|
||||
chat.MemberIDs = slices.Clone(chat.MemberIDs)
|
||||
|
||||
return chat
|
||||
}
|
||||
Reference in New Issue
Block a user