forked from mtusi2026/mtusi2026lab2
сделана пагинация чатов
This commit is contained in:
@@ -153,3 +153,71 @@ type ChatPage struct {
|
||||
Items []Chat `json:"items"`
|
||||
NextCursor *string `json:"next_cursor"`
|
||||
}
|
||||
|
||||
const chatCursorVersion = "v1"
|
||||
|
||||
type ChatCursorData struct {
|
||||
CreatedAt time.Time
|
||||
ChatID string
|
||||
UserID string
|
||||
}
|
||||
|
||||
// EncodeChatCursor создаёт непрозрачную границу списка чатов.
|
||||
// Версия позволяет в будущем изменить внутренний формат курсора.
|
||||
func EncodeChatCursor(createdAt time.Time, chatID, userID string) string {
|
||||
raw := fmt.Sprintf(
|
||||
"%s|%s|%s|%s",
|
||||
chatCursorVersion,
|
||||
createdAt.UTC().Format(time.RFC3339Nano),
|
||||
chatID,
|
||||
userID,
|
||||
)
|
||||
|
||||
// RawURLEncoding не использует символы +, / и завершающий =,
|
||||
// поэтому курсор безопаснее передавать в query string.
|
||||
return base64.RawURLEncoding.EncodeToString([]byte(raw))
|
||||
}
|
||||
|
||||
func DecodeChatCursor(
|
||||
cursorStr string,
|
||||
expectedUserID string,
|
||||
) (*ChatCursorData, error) {
|
||||
decoded, err := base64.RawURLEncoding.DecodeString(cursorStr)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("invalid base64 chat cursor")
|
||||
}
|
||||
|
||||
parts := strings.Split(string(decoded), "|")
|
||||
if len(parts) != 4 {
|
||||
return nil, fmt.Errorf("malformed chat cursor")
|
||||
}
|
||||
|
||||
if parts[0] != chatCursorVersion {
|
||||
return nil, fmt.Errorf("unsupported chat cursor version")
|
||||
}
|
||||
|
||||
createdAt, err := time.Parse(time.RFC3339Nano, parts[1])
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("invalid chat cursor timestamp")
|
||||
}
|
||||
|
||||
chatID := parts[2]
|
||||
if _, err = uuid.Parse(chatID); err != nil {
|
||||
return nil, fmt.Errorf("invalid chat cursor chat_id")
|
||||
}
|
||||
|
||||
userID := parts[3]
|
||||
if _, err = uuid.Parse(userID); err != nil {
|
||||
return nil, fmt.Errorf("invalid chat cursor user_id")
|
||||
}
|
||||
|
||||
if userID != expectedUserID {
|
||||
return nil, fmt.Errorf("chat cursor belongs to another user")
|
||||
}
|
||||
|
||||
return &ChatCursorData{
|
||||
CreatedAt: createdAt,
|
||||
ChatID: chatID,
|
||||
UserID: userID,
|
||||
}, nil
|
||||
}
|
||||
|
||||
+71
-15
@@ -12,8 +12,9 @@ import (
|
||||
)
|
||||
|
||||
var (
|
||||
ErrNotFound = fmt.Errorf("not found")
|
||||
ErrConflict = fmt.Errorf("conflict")
|
||||
ErrNotFound = fmt.Errorf("not found")
|
||||
ErrConflict = fmt.Errorf("conflict")
|
||||
ErrInvalidCursor = fmt.Errorf("invalid cursor")
|
||||
)
|
||||
|
||||
type MemoryStore struct {
|
||||
@@ -122,33 +123,88 @@ func (s *MemoryStore) GetChatByID(chatID, callerID string) (domain.Chat, error)
|
||||
return chat, nil
|
||||
}
|
||||
|
||||
func (s *MemoryStore) GetChatsForUser(userID string, limit int) ([]domain.Chat, error) {
|
||||
func (s *MemoryStore) GetChatsForUser(
|
||||
userID string,
|
||||
limit int,
|
||||
cursorStr string,
|
||||
) (domain.ChatPage, error) {
|
||||
var cursorData *domain.ChatCursorData
|
||||
|
||||
if cursorStr != "" {
|
||||
decodedCursor, err := domain.DecodeChatCursor(cursorStr, userID)
|
||||
if err != nil {
|
||||
return domain.ChatPage{},
|
||||
fmt.Errorf("%w: %v", ErrInvalidCursor, err)
|
||||
}
|
||||
|
||||
cursorData = decodedCursor
|
||||
}
|
||||
|
||||
s.mu.RLock()
|
||||
defer s.mu.RUnlock()
|
||||
|
||||
var result []domain.Chat
|
||||
chats := make([]domain.Chat, 0)
|
||||
|
||||
for _, chat := range s.chatsByID {
|
||||
for _, m := range chat.MemberIDs {
|
||||
if m == userID {
|
||||
result = append(result, chat)
|
||||
for _, memberID := range chat.MemberIDs {
|
||||
if memberID == userID {
|
||||
chats = append(chats, chat)
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
//по контракту: сортировка по created_at, id по возрастанию
|
||||
sort.Slice(result, func(i, j int) bool {
|
||||
if result[i].CreatedAt.Equal(result[j].CreatedAt) {
|
||||
return result[i].ID < result[j].ID
|
||||
sort.Slice(chats, func(i, j int) bool {
|
||||
if chats[i].CreatedAt.Equal(chats[j].CreatedAt) {
|
||||
return chats[i].ID < chats[j].ID
|
||||
}
|
||||
return result[i].CreatedAt.Before(result[j].CreatedAt)
|
||||
|
||||
return chats[i].CreatedAt.Before(chats[j].CreatedAt)
|
||||
})
|
||||
|
||||
if limit > 0 && len(result) > limit {
|
||||
result = result[:limit]
|
||||
start := 0
|
||||
|
||||
if cursorData != nil {
|
||||
start = sort.Search(len(chats), func(index int) bool {
|
||||
chat := chats[index]
|
||||
|
||||
if chat.CreatedAt.After(cursorData.CreatedAt) {
|
||||
return true
|
||||
}
|
||||
|
||||
return chat.CreatedAt.Equal(cursorData.CreatedAt) &&
|
||||
chat.ID > cursorData.ChatID
|
||||
})
|
||||
}
|
||||
|
||||
return result, nil
|
||||
page := domain.ChatPage{
|
||||
Items: make([]domain.Chat, 0),
|
||||
NextCursor: nil,
|
||||
}
|
||||
|
||||
if start >= len(chats) {
|
||||
return page, nil
|
||||
}
|
||||
|
||||
end := start + limit
|
||||
if end > len(chats) {
|
||||
end = len(chats)
|
||||
}
|
||||
|
||||
page.Items = make([]domain.Chat, end-start)
|
||||
copy(page.Items, chats[start:end])
|
||||
|
||||
if end < len(chats) {
|
||||
lastChat := page.Items[len(page.Items)-1]
|
||||
nextCursor := domain.EncodeChatCursor(
|
||||
lastChat.CreatedAt,
|
||||
lastChat.ID,
|
||||
userID,
|
||||
)
|
||||
page.NextCursor = &nextCursor
|
||||
}
|
||||
|
||||
return page, nil
|
||||
}
|
||||
|
||||
// ---Сообщения---
|
||||
|
||||
@@ -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