forked from mtusi2026/mtusi2026lab4
87 lines
1.8 KiB
Go
87 lines
1.8 KiB
Go
// Package chats implements chat creation, lookup and cursor-paginated listing.
|
|
package chats
|
|
|
|
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 CreateChatRequest struct {
|
|
Title string `json:"title"`
|
|
MemberIDs []uuid.UUID `json:"member_ids"`
|
|
}
|
|
|
|
func (h *Handler) CreateChat(c fiber.Ctx) error {
|
|
userID := common.MustUserID(c)
|
|
|
|
var req CreateChatRequest
|
|
if err := common.BindJSON(c, &req, h.jsonBodyLimit); err != nil {
|
|
return err
|
|
}
|
|
|
|
if err := common.ValidateChatTitle(req.Title); err != nil {
|
|
return err
|
|
}
|
|
if err := common.ValidateMemberIDs(req.MemberIDs, userID); err != nil {
|
|
return err
|
|
}
|
|
|
|
chat, err := h.store.CreateChat(c.Context(), req.Title, req.MemberIDs)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
return c.Status(fiber.StatusCreated).JSON(chat)
|
|
}
|
|
|
|
func (h *Handler) ListChats(c fiber.Ctx) error {
|
|
userID := common.MustUserID(c)
|
|
|
|
limit, err := common.ParseLimit(c, 50)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
cursor, err := common.ParseCursor(c)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if cursor != nil && cursor.ContextID != userID {
|
|
return common.BadRequest("bad cursor value")
|
|
}
|
|
|
|
page, err := h.store.ListChats(c.Context(), userID, limit, cursor)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
return c.JSON(page)
|
|
}
|
|
|
|
func (h *Handler) GetChat(c fiber.Ctx) error {
|
|
userID := common.MustUserID(c)
|
|
|
|
chatID, err := common.PathUUID(c, "chat_id")
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
chat, err := h.store.GetChatForUser(c.Context(), userID, chatID)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
return c.JSON(chat)
|
|
}
|