forked from mtusi2026/mtusi2026lab3
77 lines
1.5 KiB
Go
77 lines
1.5 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"
|
|
)
|
|
|
|
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 := 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); err != nil {
|
|
return err
|
|
}
|
|
if err := common.ValidateMessageText(req.Text); err != nil {
|
|
return err
|
|
}
|
|
|
|
message, err := h.store.CreateMessage(c.Context(), chatID, userID, req.Text, idempotencyKey)
|
|
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)
|
|
}
|