forked from mtusi2026/mtusi2026lab6
89 lines
1.8 KiB
Go
89 lines
1.8 KiB
Go
package handler
|
|
|
|
import (
|
|
"net/http"
|
|
"regexp"
|
|
|
|
"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"
|
|
)
|
|
|
|
var idempotencyKeyPattern = regexp.MustCompile(`^[A-Za-z0-9._:-]{1,128}$`)
|
|
|
|
type MessageHandler struct {
|
|
messages *service.MessageService
|
|
}
|
|
|
|
func NewMessageHandler(messages *service.MessageService) *MessageHandler {
|
|
return &MessageHandler{messages: messages}
|
|
}
|
|
|
|
func (h *MessageHandler) Create(c *gin.Context) {
|
|
var req dto.CreateMessageRequest
|
|
if err := bindStrictJSON(c, &req); err != nil {
|
|
respondError(c, err)
|
|
return
|
|
}
|
|
|
|
key := c.GetHeader("Idempotency-Key")
|
|
if key == "" || !idempotencyKeyPattern.MatchString(key) {
|
|
respondError(c, &badRequestError{
|
|
msg: "Idempotency-Key обязателен и должен соответствовать ^[A-Za-z0-9._:-]{1,128}$",
|
|
})
|
|
return
|
|
}
|
|
|
|
me := middleware.CurrentUser(c)
|
|
|
|
chatID, err := parseUUIDPathParam(c, "chat_id")
|
|
if err != nil {
|
|
respondError(c, err)
|
|
return
|
|
}
|
|
|
|
result, err := h.messages.Create(
|
|
c.Request.Context(),
|
|
me.ID,
|
|
chatID,
|
|
req.Text,
|
|
req.AttachmentIDs,
|
|
key,
|
|
c.Request.URL.Path,
|
|
)
|
|
if err != nil {
|
|
respondError(c, err)
|
|
return
|
|
}
|
|
|
|
c.Data(result.Status, "application/json", result.Body)
|
|
}
|
|
|
|
func (h *MessageHandler) List(c *gin.Context) {
|
|
me := middleware.CurrentUser(c)
|
|
|
|
chatID, err := parseUUIDPathParam(c, "chat_id")
|
|
if err != nil {
|
|
respondError(c, err)
|
|
return
|
|
}
|
|
|
|
limit, cursor, err := parseListQuery(c)
|
|
if err != nil {
|
|
respondError(c, err)
|
|
return
|
|
}
|
|
|
|
items, next, err := h.messages.List(c.Request.Context(), me.ID, chatID, limit, cursor)
|
|
if err != nil {
|
|
respondError(c, err)
|
|
return
|
|
}
|
|
c.JSON(http.StatusOK, dto.MessagePageResponse{
|
|
Items: dto.MessagesFromDomain(items),
|
|
NextCursor: next,
|
|
})
|
|
}
|