lab 3 done
This commit is contained in:
@@ -0,0 +1,70 @@
|
||||
package chat
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/labstack/echo/v4"
|
||||
|
||||
"gitflic.ru/akselbant/mtusi2026lab1-fork/dto"
|
||||
"gitflic.ru/akselbant/mtusi2026lab1-fork/internal/pkg/domain"
|
||||
)
|
||||
|
||||
func (h *Chat) listMessages(c echo.Context) error {
|
||||
request := dto.ListMessagesRequest{ChatID: c.Param("chat_id")}
|
||||
chat, ok, err := h.authorizedChat(c, domain.Chat{ID: request.ChatID})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
limit, err := parseLimit(c)
|
||||
if err != nil {
|
||||
return h.invalid(c, err.Error())
|
||||
}
|
||||
rawCursor, cursorPresent, err := oneQueryValue(c, "cursor")
|
||||
if err != nil {
|
||||
return h.invalid(c, "cursor должен быть указан один раз")
|
||||
}
|
||||
request.ChatID = chat.ID
|
||||
request.Limit = limit
|
||||
request.Cursor = rawCursor
|
||||
position, err := h.cursorPosition(request.Cursor, cursorPresent, "messages", request.ChatID)
|
||||
if err != nil {
|
||||
return h.invalid(c, "Некорректный cursor")
|
||||
}
|
||||
|
||||
page, err := h.useCase.ListMessages(
|
||||
c.Request().Context(), authenticatedUser(c).ID,
|
||||
listMessagesChatToDomain(request), listMessagesPaginationToDomain(request, position),
|
||||
)
|
||||
if err != nil {
|
||||
return h.useCaseError(c, err)
|
||||
}
|
||||
var next *string
|
||||
if page.HasMore {
|
||||
last := page.Items[len(page.Items)-1]
|
||||
encoded := h.cursor.encode("messages", request.ChatID, last.CreatedAt, last.ID)
|
||||
next = &encoded
|
||||
}
|
||||
return c.JSON(http.StatusOK, listMessagesResponseFromDomain(page, next))
|
||||
}
|
||||
|
||||
func listMessagesChatToDomain(request dto.ListMessagesRequest) domain.Chat {
|
||||
return domain.Chat{ID: request.ChatID}
|
||||
}
|
||||
|
||||
func listMessagesPaginationToDomain(request dto.ListMessagesRequest, position *domain.Position) domain.Pagination {
|
||||
return domain.Pagination{After: position, Limit: request.Limit}
|
||||
}
|
||||
|
||||
func listMessagesResponseFromDomain(page domain.MessagePage, nextCursor *string) dto.ListMessagesResponse {
|
||||
items := make([]dto.ListMessagesItem, 0, len(page.Items))
|
||||
for _, message := range page.Items {
|
||||
items = append(items, dto.ListMessagesItem{
|
||||
ID: message.ID, ChatID: message.ChatID, SenderID: message.SenderID,
|
||||
Text: message.Text, CreatedAt: dto.Timestamp(message.CreatedAt),
|
||||
})
|
||||
}
|
||||
return dto.ListMessagesResponse{Items: items, NextCursor: nextCursor}
|
||||
}
|
||||
Reference in New Issue
Block a user