forked from mtusi2026/mtusi2026lab2
сделана пагинация чатов
This commit is contained in:
@@ -73,32 +73,65 @@ func (h *Handler) GetChat(w http.ResponseWriter, r *http.Request) {
|
||||
func (h *Handler) ListChats(w http.ResponseWriter, r *http.Request) {
|
||||
reqID := middleware.GetRequestID(r.Context())
|
||||
currentUser := middleware.GetCurrentUser(r.Context())
|
||||
query := r.URL.Query()
|
||||
|
||||
limit := 50
|
||||
limitStr := r.URL.Query().Get("limit")
|
||||
if limitStr != "" {
|
||||
|
||||
if query.Has("limit") {
|
||||
limitStr := query.Get("limit")
|
||||
val, err := strconv.Atoi(limitStr)
|
||||
|
||||
if err != nil || val < 1 || val > 100 {
|
||||
response.WriteError(w, http.StatusBadRequest, response.CodeInvalidRequest, "limit must be an integer between 1 and 100", reqID)
|
||||
response.WriteError(
|
||||
w,
|
||||
http.StatusBadRequest,
|
||||
response.CodeInvalidRequest,
|
||||
"limit must be an integer between 1 and 100",
|
||||
reqID,
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
limit = val
|
||||
}
|
||||
|
||||
chats, err := h.store.GetChatsForUser(currentUser.ID, limit)
|
||||
if err != nil {
|
||||
response.WriteError(w, http.StatusInternalServerError, response.CodeInternalError, "internal error", reqID)
|
||||
cursor := query.Get("cursor")
|
||||
if query.Has("cursor") && cursor == "" {
|
||||
response.WriteError(
|
||||
w,
|
||||
http.StatusBadRequest,
|
||||
response.CodeInvalidRequest,
|
||||
"cursor must not be empty",
|
||||
reqID,
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
//если чатов нет, сериализую в пустой массив [], а не null
|
||||
if chats == nil {
|
||||
chats = make([]domain.Chat, 0)
|
||||
}
|
||||
page, err := h.store.GetChatsForUser(
|
||||
currentUser.ID,
|
||||
limit,
|
||||
cursor,
|
||||
)
|
||||
if err != nil {
|
||||
if errors.Is(err, store.ErrInvalidCursor) {
|
||||
response.WriteError(
|
||||
w,
|
||||
http.StatusBadRequest,
|
||||
response.CodeInvalidRequest,
|
||||
"invalid cursor",
|
||||
reqID,
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
page := domain.ChatPage{
|
||||
Items: chats,
|
||||
NextCursor: nil,
|
||||
response.WriteError(
|
||||
w,
|
||||
http.StatusInternalServerError,
|
||||
response.CodeInternalError,
|
||||
"internal error",
|
||||
reqID,
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
response.WriteJSON(w, http.StatusOK, page, reqID)
|
||||
|
||||
Reference in New Issue
Block a user