forked from mtusi2026/mtusi2026lab3
feat(messages): make message creation idempotent
This commit is contained in:
@@ -3,6 +3,7 @@ package handler
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
"regexp"
|
||||
|
||||
"github.com/go-chi/chi/v5"
|
||||
"github.com/google/uuid"
|
||||
@@ -13,6 +14,8 @@ import (
|
||||
"mtusi2026-messenger/internal/service"
|
||||
)
|
||||
|
||||
var idempotencyKeyReq = regexp.MustCompile(`^[A-Za-z0-9._:-]{1,128}$`)
|
||||
|
||||
type MessageHandler struct {
|
||||
service *service.MessageService
|
||||
}
|
||||
@@ -37,6 +40,18 @@ func (h *MessageHandler) Create(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
|
||||
key := r.Header.Get("Idempotency-Key")
|
||||
if !idempotencyKeyReq.MatchString(key) {
|
||||
httpx.WriteError(
|
||||
w,
|
||||
http.StatusBadRequest,
|
||||
dto.ErrorCodeInvalidRequest,
|
||||
"invalid Idempotency-Key",
|
||||
requestID,
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
var req dto.CreateMessageRequest
|
||||
if !httpx.DecodeJSONBody(w, r, requestID, &req) {
|
||||
return
|
||||
@@ -53,7 +68,7 @@ func (h *MessageHandler) Create(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
|
||||
message, err := h.service.Create(r.Context(), userID, chatID, req.Text)
|
||||
message, err := h.service.Create(r.Context(), userID, chatID, key, req.Text)
|
||||
switch {
|
||||
case errors.Is(err, service.ErrMessageChatNotFound):
|
||||
httpx.WriteError(
|
||||
@@ -64,6 +79,15 @@ func (h *MessageHandler) Create(w http.ResponseWriter, r *http.Request) {
|
||||
requestID,
|
||||
)
|
||||
return
|
||||
case errors.Is(err, service.ErrIdempotencyKeyConflict):
|
||||
httpx.WriteError(
|
||||
w,
|
||||
http.StatusConflict,
|
||||
dto.ErrorCodeConflict,
|
||||
"idempotency key reused with different request",
|
||||
requestID,
|
||||
)
|
||||
return
|
||||
case err != nil:
|
||||
httpx.WriteInternalError(w, requestID, err)
|
||||
return
|
||||
|
||||
Reference in New Issue
Block a user