forked from mtusi2026/mtusi2026lab4
chore(solution): port lab3 sources
This commit is contained in:
@@ -0,0 +1,81 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"uuid"
|
||||
|
||||
"messenger/internal/domain"
|
||||
)
|
||||
|
||||
type ChatService struct {
|
||||
repo ChatRepository
|
||||
}
|
||||
|
||||
func NewChatService(repo ChatRepository) *ChatService {
|
||||
return &ChatService{repo: repo}
|
||||
}
|
||||
|
||||
func (s *ChatService) Create(ctx context.Context, actor domain.User, title string, memberIDs []uuid.UUID) (domain.Chat, error) {
|
||||
if err := checkText("title", title, 100); err != nil {
|
||||
return domain.Chat{}, err
|
||||
}
|
||||
if len(memberIDs) < 1 || len(memberIDs) > 100 {
|
||||
return domain.Chat{}, fmt.Errorf("%w: member_ids must contain 1 to 100 users", domain.ErrInvalidInput)
|
||||
}
|
||||
seen := make(map[uuid.UUID]struct{}, len(memberIDs))
|
||||
for _, id := range memberIDs {
|
||||
if _, dup := seen[id]; dup {
|
||||
return domain.Chat{}, fmt.Errorf("%w: member_ids must not contain duplicates", domain.ErrInvalidInput)
|
||||
}
|
||||
seen[id] = struct{}{}
|
||||
}
|
||||
if _, ok := seen[actor.ID]; !ok {
|
||||
return domain.Chat{}, fmt.Errorf("%w: member_ids must include the current user", domain.ErrInvalidInput)
|
||||
}
|
||||
|
||||
c := domain.Chat{
|
||||
ID: uuid.New(),
|
||||
Title: title,
|
||||
MemberIDs: memberIDs,
|
||||
CreatedAt: now(),
|
||||
}
|
||||
if err := s.repo.CreateChat(ctx, c); err != nil {
|
||||
if errors.Is(err, domain.ErrNotFound) {
|
||||
return domain.Chat{}, fmt.Errorf("%w: member_ids contains unknown user", domain.ErrInvalidInput)
|
||||
}
|
||||
return domain.Chat{}, err
|
||||
}
|
||||
return c, nil
|
||||
}
|
||||
|
||||
func (s *ChatService) Get(ctx context.Context, actor domain.User, chatID uuid.UUID) (domain.Chat, error) {
|
||||
c, err := s.repo.GetChat(ctx, chatID)
|
||||
if err != nil {
|
||||
return domain.Chat{}, err
|
||||
}
|
||||
if !c.HasMember(actor.ID) {
|
||||
return domain.Chat{}, domain.ErrNotFound
|
||||
}
|
||||
return c, nil
|
||||
}
|
||||
|
||||
func (s *ChatService) List(ctx context.Context, actor domain.User, after *domain.Cursor, limit int) (domain.Page[domain.Chat], error) {
|
||||
if err := checkLimit(limit); err != nil {
|
||||
return domain.Page[domain.Chat]{}, err
|
||||
}
|
||||
if after != nil && after.Scope != actor.ID {
|
||||
return domain.Page[domain.Chat]{}, fmt.Errorf("%w: cursor does not belong to this request", domain.ErrInvalidInput)
|
||||
}
|
||||
items, more, err := s.repo.ListUserChats(ctx, actor.ID, after, limit)
|
||||
if err != nil {
|
||||
return domain.Page[domain.Chat]{}, err
|
||||
}
|
||||
page := domain.Page[domain.Chat]{Items: items}
|
||||
if more {
|
||||
last := items[len(items)-1]
|
||||
page.Next = &domain.Cursor{Scope: actor.ID, CreatedAt: last.CreatedAt, ID: last.ID}
|
||||
}
|
||||
return page, nil
|
||||
}
|
||||
Reference in New Issue
Block a user