Files
mtusi2026lab4/app/internal/messages/handler.go
T
2026-11-06 19:06:21 +03:00

83 lines
1.8 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
jsonBodyLimit int64
}
func NewHandler(st *store.Store, jsonBodyLimit int64) *Handler {
return &Handler{store: st, jsonBodyLimit: jsonBodyLimit}
}
type CreateMessageRequest struct {
Text string `json:"text"`
AttachmentIDs []uuid.UUID `json:"attachment_ids"`
}
func (h *Handler) CreateMessage(c fiber.Ctx) error {
userID := common.MustUserID(c)
chatID, err := common.PathUUID(c, "chat_id")
if err != nil {
return err
}
idempotencyKey := c.Get("Idempotency-Key")
if err := common.ValidateIdempotencyKey(idempotencyKey); err != nil {
return err
}
var req CreateMessageRequest
if err := common.BindJSON(c, &req, h.jsonBodyLimit); err != nil {
return err
}
if err := common.ValidateAttachmentIDs(req.AttachmentIDs); err != nil {
return err
}
if err := common.ValidateMessageText(req.Text, len(req.AttachmentIDs)); err != nil {
return err
}
message, err := h.store.CreateMessage(c.Context(), chatID, userID, req.Text, idempotencyKey, req.AttachmentIDs)
if err != nil {
return err
}
return c.Status(fiber.StatusCreated).JSON(message)
}
func (h *Handler) ListMessages(c fiber.Ctx) error {
userID := common.MustUserID(c)
chatID, err := common.PathUUID(c, "chat_id")
if err != nil {
return err
}
limit, err := common.ParseLimit(c, 50)
if err != nil {
return err
}
cursor, err := common.ParseCursor(c)
if err != nil {
return err
}
page, err := h.store.ListMessages(c.Context(), userID, chatID, limit, cursor)
if err != nil {
return err
}
return c.JSON(page)
}