101 lines
2.2 KiB
Go
101 lines
2.2 KiB
Go
package service
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"net/http"
|
|
"strings"
|
|
"time"
|
|
"unicode/utf8"
|
|
|
|
"github.com/google/uuid"
|
|
|
|
"high-loud-apps-labs/internal/domain"
|
|
"high-loud-apps-labs/internal/httpapi/dto"
|
|
)
|
|
|
|
type MessageService struct {
|
|
messages domain.MessageRepository
|
|
chats domain.ChatRepository
|
|
idempotencyTTL time.Duration
|
|
}
|
|
|
|
func NewMessageService(
|
|
messages domain.MessageRepository,
|
|
chats domain.ChatRepository,
|
|
idempotencyTTL time.Duration,
|
|
) *MessageService {
|
|
return &MessageService{
|
|
messages: messages,
|
|
chats: chats,
|
|
idempotencyTTL: idempotencyTTL,
|
|
}
|
|
}
|
|
|
|
func (s *MessageService) Create(ctx context.Context, senderID, chatID, text, idempotencyKey, requestPath string,
|
|
) (*domain.CreateIdempotentResult, error) {
|
|
if strings.TrimSpace(text) == "" {
|
|
return nil, &domain.ValidationError{
|
|
Field: "text",
|
|
Message: "не может состоять только из пробелов",
|
|
}
|
|
}
|
|
if utf8.RuneCountInString(text) > 4000 {
|
|
return nil, &domain.ValidationError{
|
|
Field: "text",
|
|
Message: "не более 4000 символов",
|
|
}
|
|
}
|
|
|
|
if err := s.ensureMember(ctx, senderID, chatID); err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
fresh := &domain.Message{
|
|
ID: uuid.NewString(),
|
|
ChatID: chatID,
|
|
SenderID: senderID,
|
|
Text: text,
|
|
CreatedAt: time.Now().UTC(),
|
|
}
|
|
|
|
body, err := json.Marshal(dto.MessageFromDomain(fresh))
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
return s.messages.CreateIdempotent(
|
|
ctx,
|
|
domain.IdempotencyScope{
|
|
UserID: senderID,
|
|
Method: http.MethodPost,
|
|
Path: requestPath,
|
|
Key: idempotencyKey,
|
|
},
|
|
domain.RequestHash(text),
|
|
fresh,
|
|
body,
|
|
s.idempotencyTTL,
|
|
)
|
|
}
|
|
|
|
func (s *MessageService) List(ctx context.Context, userID, chatID string, limit int, cursor *string) ([]domain.Message, *string, error) {
|
|
if err := s.ensureMember(ctx, userID, chatID); err != nil {
|
|
return nil, nil, err
|
|
}
|
|
return s.messages.ListByChat(ctx, chatID, limit, cursor)
|
|
}
|
|
|
|
func (s *MessageService) ensureMember(ctx context.Context, userID, chatID string) error {
|
|
c, err := s.chats.GetByID(ctx, chatID)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
for _, m := range c.MemberIDs {
|
|
if m == userID {
|
|
return nil
|
|
}
|
|
}
|
|
return &domain.NotFoundError{Entity: "chat", ID: chatID}
|
|
}
|