forked from mtusi2026/mtusi2026lab7
на оценку 4
This commit is contained in:
@@ -0,0 +1,88 @@
|
||||
package application
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
|
||||
"mtusi2026lab7/internal/domain"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
type canonicalMessageRequest struct {
|
||||
Text string `json:"text"`
|
||||
AttachmentIDs []string `json:"attachment_ids"`
|
||||
}
|
||||
|
||||
func (s *Service) SendMessage(ctx context.Context, command SendMessageCommand) (domain.Message, error) {
|
||||
attachmentIDs := append([]string(nil), command.AttachmentIDs...)
|
||||
if attachmentIDs == nil {
|
||||
attachmentIDs = make([]string, 0)
|
||||
}
|
||||
|
||||
if err := domain.ValidateMessageInput(command.Text, attachmentIDs); err != nil {
|
||||
return domain.Message{}, fmt.Errorf("%w: %v", ErrInvalidInput, err)
|
||||
}
|
||||
for index, attachmentID := range attachmentIDs {
|
||||
attachmentIDs[index] = uuid.MustParse(attachmentID).String()
|
||||
}
|
||||
|
||||
canonicalBody, err := json.Marshal(canonicalMessageRequest{
|
||||
Text: command.Text,
|
||||
AttachmentIDs: attachmentIDs,
|
||||
})
|
||||
if err != nil {
|
||||
return domain.Message{}, fmt.Errorf("canonicalize message request: %w", err)
|
||||
}
|
||||
|
||||
return s.repository.CreateMessageIdempotently(ctx, IdempotentMessageWrite{
|
||||
ActorID: command.ActorID,
|
||||
ChatID: command.ChatID,
|
||||
Text: command.Text,
|
||||
AttachmentIDs: attachmentIDs,
|
||||
Method: command.Method,
|
||||
CanonicalPath: command.CanonicalPath,
|
||||
Key: command.IdempotencyKey,
|
||||
RequestHash: sha256.Sum256(canonicalBody),
|
||||
TTL: s.idempotencyTTL,
|
||||
})
|
||||
}
|
||||
|
||||
func (s *Service) ListMessages(
|
||||
ctx context.Context,
|
||||
actorID string,
|
||||
chatID string,
|
||||
limit int,
|
||||
cursorToken string,
|
||||
) (domain.MessagePage, error) {
|
||||
var cursor *domain.MessageCursor
|
||||
if cursorToken != "" {
|
||||
decoded, err := s.cursors.DecodeMessage(cursorToken, chatID)
|
||||
if err != nil {
|
||||
return domain.MessagePage{}, ErrInvalidCursor
|
||||
}
|
||||
cursor = decoded
|
||||
}
|
||||
|
||||
items, hasMore, err := s.repository.GetMessages(ctx, chatID, actorID, limit, cursor)
|
||||
if err != nil {
|
||||
return domain.MessagePage{}, err
|
||||
}
|
||||
page := domain.MessagePage{Items: items}
|
||||
if page.Items == nil {
|
||||
page.Items = make([]domain.Message, 0)
|
||||
}
|
||||
if hasMore {
|
||||
last := page.Items[len(page.Items)-1]
|
||||
next, encodeErr := s.cursors.EncodeMessage(domain.MessageCursor{
|
||||
CreatedAt: last.CreatedAt, MessageID: last.ID, ChatID: chatID,
|
||||
})
|
||||
if encodeErr != nil {
|
||||
return domain.MessagePage{}, encodeErr
|
||||
}
|
||||
page.NextCursor = &next
|
||||
}
|
||||
return page, nil
|
||||
}
|
||||
Reference in New Issue
Block a user