forked from mtusi2026/mtusi2026lab2
73 lines
1.7 KiB
Go
73 lines
1.7 KiB
Go
package messages
|
|
|
|
import (
|
|
"gitflic.ru/project/bulla-max/mtusi2026lab2/internal/common"
|
|
"gitflic.ru/project/bulla-max/mtusi2026lab2/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")
|
|
}
|
|
|
|
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)
|
|
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)
|
|
}
|