Files
mtusi2026lab3/app/internal/messages/handler.go
T
2026-10-30 18:11:30 +03:00

80 lines
2.0 KiB
Go

// Package messages implements message creation with idempotency and message
// history pagination.
package messages
import (
"gitflic.ru/project/bulla-max/mtusi2026lab/internal/common"
"gitflic.ru/project/bulla-max/mtusi2026lab/internal/store"
"github.com/gofiber/fiber/v3"
"github.com/google/uuid"
)
type Handler struct {
store *store.Store
}
func NewHandler(st *store.Store) *Handler {
return &Handler{store: st}
}
type CreateMessageRequest struct {
Text string `json:"text"`
}
func (h *Handler) CreateMessage(c fiber.Ctx) error {
userID := common.MustUserID(c)
chatID, err := uuid.Parse(c.Params("chat_id"))
if err != nil {
return common.SendError(c, fiber.StatusBadRequest,
common.ErrorCodeInvalidRequest, "invalid chat_id format")
}
idempotencyKey := c.Get("Idempotency-Key")
if msg := common.ValidateIdempotencyKey(idempotencyKey); msg != "" {
return common.SendError(c, fiber.StatusBadRequest, common.ErrorCodeInvalidRequest, msg)
}
var req CreateMessageRequest
if err := common.BindJSON(c, &req); err != nil {
return common.SendAppError(c, err)
}
if msg := common.ValidateMessageText(req.Text); msg != "" {
return common.SendError(c, fiber.StatusBadRequest, common.ErrorCodeInvalidRequest, msg)
}
message, err := h.store.CreateMessage(c.Context(), chatID, userID, req.Text, idempotencyKey)
if err != nil {
return common.SendAppError(c, err)
}
return c.Status(fiber.StatusCreated).JSON(message)
}
func (h *Handler) ListMessages(c fiber.Ctx) error {
userID := common.MustUserID(c)
chatID, err := uuid.Parse(c.Params("chat_id"))
if err != nil {
return common.SendError(c, fiber.StatusBadRequest,
common.ErrorCodeInvalidRequest, "invalid chat_id format")
}
limit, err := common.ParseLimit(c, 50)
if err != nil {
return common.SendAppError(c, err)
}
cursor, err := common.ParseCursor(c)
if err != nil {
return common.SendAppError(c, err)
}
page, err := h.store.ListMessages(c.Context(), userID, chatID, limit, cursor)
if err != nil {
return common.SendAppError(c, err)
}
return c.JSON(page)
}