Files
mtusi2026lab2/internal/transport/http/handler/message.go
T
OlegRood 834876c938 ЛР 2: закрыть уровень 4
Завершить PostgreSQL, Redis-сессии, миграции, таймауты и диагностику. Зафиксировать собственные тесты и доказательства финального прогона: 43 PASS, 0 FAIL, 0 SKIP; 768 HTTP-запросов без ошибок. Добавить официальный отчёт с запуском, архитектурой, SQL-планами и ограничениями. PR отложен до завершения уровня 5.
2026-10-28 13:30:26 +03:00

80 lines
2.3 KiB
Go

package handler
import (
"highload/internal/service"
"highload/internal/transport/http/httputils"
"highload/internal/transport/http/middleware"
"net/http"
)
type MessageHandler struct {
messageService *service.MessageService
}
func NewMessageHandler(messageService *service.MessageService) *MessageHandler {
return &MessageHandler{messageService: messageService}
}
func (h *MessageHandler) CreateMessage(w http.ResponseWriter, r *http.Request) {
requestID := middleware.RequestIDFromContext(r.Context())
userID := middleware.UserIDFromContext(r.Context())
chatID := r.PathValue("chat_id")
req, code := httputils.Decode[messageCreateRequest](r)
if code != http.StatusOK {
if code == http.StatusUnsupportedMediaType {
httputils.WriteError(w, code, httputils.ErrorDetails{Code: "unsupported_media_type", Message: "Неверный media type", RequestID: requestID})
return
}
httputils.WriteError(w, code, httputils.ErrorDetails{Code: "invalid_request", Message: "Неверный запрос", RequestID: requestID})
return
}
message, err := h.messageService.CreateMessage(r.Context(), req.Text, chatID, userID)
if err != nil {
httputils.WriteServiceError(w, err, requestID)
return
}
response := convertMessageModelToResponse(message)
_ = httputils.WriteJSON[messageResponse](w, http.StatusCreated, *response)
}
func (h *MessageHandler) GetMessagesByChatID(w http.ResponseWriter, r *http.Request) {
requestID := middleware.RequestIDFromContext(r.Context())
userID := middleware.UserIDFromContext(r.Context())
chatID := r.PathValue("chat_id")
limit, cursor, ok := httputils.GetLimitAndCursor(r)
if !ok {
httputils.WriteError(w, http.StatusBadRequest, httputils.ErrorDetails{Code: "invalid_request", Message: "Неверный запрос", RequestID: requestID})
return
}
messages, nextCursor, err := h.messageService.GetMessagesByChatID(r.Context(), chatID, userID, limit, cursor)
if err != nil {
httputils.WriteServiceError(w, err, requestID)
return
}
messageResponses := make([]messageResponse, len(messages))
for index, message := range messages {
messageResponses[index] = *convertMessageModelToResponse(message)
}
response := messageGetResponse{
Items: messageResponses,
NextCursor: nextCursor,
}
_ = httputils.WriteJSON[messageGetResponse](w, http.StatusOK, response)
}