89 lines
1.9 KiB
Go
89 lines
1.9 KiB
Go
package handler
|
|
|
|
import (
|
|
"net/http"
|
|
"strconv"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
|
|
"high-loud-apps-labs/internal/httpapi/dto"
|
|
"high-loud-apps-labs/internal/httpapi/middleware"
|
|
"high-loud-apps-labs/internal/service"
|
|
)
|
|
|
|
type ChatHandler struct {
|
|
chats *service.ChatService
|
|
}
|
|
|
|
func NewChatHandler(chats *service.ChatService) *ChatHandler {
|
|
return &ChatHandler{chats: chats}
|
|
}
|
|
|
|
func (h *ChatHandler) Create(c *gin.Context) {
|
|
var req dto.CreateChatRequest
|
|
if err := bindStrictJSON(c, &req); err != nil {
|
|
respondError(c, err)
|
|
return
|
|
}
|
|
me := middleware.CurrentUser(c)
|
|
|
|
chat, err := h.chats.Create(c.Request.Context(), me.ID, req.Title, req.MemberIDs)
|
|
if err != nil {
|
|
respondError(c, err)
|
|
return
|
|
}
|
|
c.JSON(http.StatusCreated, dto.ChatFromDomain(chat))
|
|
}
|
|
|
|
func (h *ChatHandler) Get(c *gin.Context) {
|
|
me := middleware.CurrentUser(c)
|
|
|
|
chatID, err := parseUUIDPathParam(c, "chat_id")
|
|
if err != nil {
|
|
respondError(c, err)
|
|
return
|
|
}
|
|
|
|
chat, err := h.chats.Get(c.Request.Context(), me.ID, chatID)
|
|
if err != nil {
|
|
respondError(c, err)
|
|
return
|
|
}
|
|
c.JSON(http.StatusOK, dto.ChatFromDomain(chat))
|
|
}
|
|
|
|
func (h *ChatHandler) List(c *gin.Context) {
|
|
me := middleware.CurrentUser(c)
|
|
limit, cursor, err := parseListQuery(c)
|
|
if err != nil {
|
|
respondError(c, err)
|
|
return
|
|
}
|
|
|
|
items, next, err := h.chats.List(c.Request.Context(), me.ID, limit, cursor)
|
|
if err != nil {
|
|
respondError(c, err)
|
|
return
|
|
}
|
|
c.JSON(http.StatusOK, dto.ChatPageResponse{
|
|
Items: dto.ChatsFromDomain(items),
|
|
NextCursor: next,
|
|
})
|
|
}
|
|
|
|
func parseListQuery(c *gin.Context) (int, *string, error) {
|
|
limit := 50
|
|
if v := c.Query("limit"); v != "" {
|
|
n, err := strconv.Atoi(v)
|
|
if err != nil || n < 1 || n > 100 {
|
|
return 0, nil, &badRequestError{msg: "limit должен быть целым 1..100"}
|
|
}
|
|
limit = n
|
|
}
|
|
var cursor *string
|
|
if v := c.Query("cursor"); v != "" {
|
|
cursor = &v
|
|
}
|
|
return limit, cursor, nil
|
|
}
|