feat(httpapi): require Idempotency-Key on POST chat messages

This commit is contained in:
Голиков Maximillian Антон
2026-10-06 23:55:36 +03:00
parent 23b5cd0c3f
commit 1695fa0f2f
3 changed files with 58 additions and 12 deletions
+36 -8
View File
@@ -2,6 +2,8 @@ package service
import (
"context"
"encoding/json"
"net/http"
"strings"
"time"
"unicode/utf8"
@@ -9,18 +11,29 @@ import (
"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
messages domain.MessageRepository
chats domain.ChatRepository
idempotencyTTL time.Duration
}
func NewMessageService(messages domain.MessageRepository, chats domain.ChatRepository) *MessageService {
return &MessageService{messages: messages, chats: chats}
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 string) (*domain.Message, error) {
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",
@@ -38,17 +51,32 @@ func (s *MessageService) Create(ctx context.Context, senderID, chatID, text stri
return nil, err
}
m := &domain.Message{
fresh := &domain.Message{
ID: uuid.NewString(),
ChatID: chatID,
SenderID: senderID,
Text: text,
CreatedAt: time.Now().UTC(),
}
if err := s.messages.Create(ctx, m); err != nil {
body, err := json.Marshal(dto.MessageFromDomain(fresh))
if err != nil {
return nil, err
}
return m, nil
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) {