import lab3 files
This commit is contained in:
@@ -0,0 +1,95 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"strings"
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"high-loud-apps-labs/internal/domain"
|
||||
)
|
||||
|
||||
type ChatService struct {
|
||||
chats domain.ChatRepository
|
||||
users domain.UserRepository
|
||||
}
|
||||
|
||||
func NewChatService(chats domain.ChatRepository, users domain.UserRepository) *ChatService {
|
||||
return &ChatService{chats: chats, users: users}
|
||||
}
|
||||
|
||||
func (s *ChatService) Create(ctx context.Context, creatorID, title string, memberIDs []string) (*domain.Chat, error) {
|
||||
if strings.TrimSpace(title) == "" {
|
||||
return nil, &domain.ValidationError{
|
||||
Field: "title",
|
||||
Message: "не может состоять только из пробелов",
|
||||
}
|
||||
}
|
||||
if utf8.RuneCountInString(title) > 100 {
|
||||
return nil, &domain.ValidationError{
|
||||
Field: "title",
|
||||
Message: "не более 100 символов",
|
||||
}
|
||||
}
|
||||
|
||||
seen := make(map[string]struct{}, len(memberIDs))
|
||||
for _, id := range memberIDs {
|
||||
if _, dup := seen[id]; dup {
|
||||
return nil, &domain.ValidationError{
|
||||
Field: "member_ids",
|
||||
Message: "дубликаты запрещены",
|
||||
}
|
||||
}
|
||||
seen[id] = struct{}{}
|
||||
}
|
||||
|
||||
if _, ok := seen[creatorID]; !ok {
|
||||
return nil, &domain.ValidationError{
|
||||
Field: "member_ids",
|
||||
Message: "создатель должен входить в список участников",
|
||||
}
|
||||
}
|
||||
|
||||
for _, id := range memberIDs {
|
||||
if _, err := s.users.GetByID(ctx, id); err != nil {
|
||||
if errors.Is(err, domain.ErrNotFound) {
|
||||
return nil, &domain.ValidationError{
|
||||
Field: "member_ids",
|
||||
Message: "неизвестный участник " + id,
|
||||
}
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
c := &domain.Chat{
|
||||
ID: uuid.NewString(),
|
||||
Title: title,
|
||||
MemberIDs: append([]string(nil), memberIDs...),
|
||||
CreatedAt: time.Now().UTC(),
|
||||
}
|
||||
if err := s.chats.Create(ctx, c); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return c, nil
|
||||
}
|
||||
|
||||
func (s *ChatService) Get(ctx context.Context, userID, chatID string) (*domain.Chat, error) {
|
||||
c, err := s.chats.GetByID(ctx, chatID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, m := range c.MemberIDs {
|
||||
if m == userID {
|
||||
return c, nil
|
||||
}
|
||||
}
|
||||
return nil, &domain.NotFoundError{Entity: "chat", ID: chatID}
|
||||
}
|
||||
|
||||
func (s *ChatService) List(ctx context.Context, userID string, limit int, cursor *string) ([]domain.Chat, *string, error) {
|
||||
return s.chats.ListByMember(ctx, userID, limit, cursor)
|
||||
}
|
||||
Reference in New Issue
Block a user