forked from mtusi2026/mtusi2026lab2
fix: address lab2 review feedback
This commit is contained in:
@@ -203,3 +203,43 @@ func (s *ChatStore) ExistsUser(
|
||||
|
||||
// Kept here to document that chat timestamps are stored in UTC.
|
||||
var _ = time.UTC
|
||||
|
||||
// ListChatsPage uses (created_at,id) keyset pagination and fetches limit+1.
|
||||
func (s *ChatStore) ListChatsPage(ctx context.Context, userID uuid.UUID, limit int, cursorTime *time.Time, cursorID *uuid.UUID) ([]model.Chat, bool, error) {
|
||||
var rows pgx.Rows
|
||||
var err error
|
||||
if cursorTime == nil || cursorID == nil {
|
||||
rows, err = s.pool.Query(ctx, `SELECT c.id,c.title,c.created_at FROM chats c JOIN chat_members cm ON cm.chat_id=c.id WHERE cm.user_id=$1 ORDER BY c.created_at,c.id LIMIT $2`, userID, limit+1)
|
||||
} else {
|
||||
rows, err = s.pool.Query(ctx, `SELECT c.id,c.title,c.created_at FROM chats c JOIN chat_members cm ON cm.chat_id=c.id WHERE cm.user_id=$1 AND (c.created_at,c.id)>($2,$3) ORDER BY c.created_at,c.id LIMIT $4`, userID, *cursorTime, *cursorID, limit+1)
|
||||
}
|
||||
if err != nil {
|
||||
return nil, false, fmt.Errorf("list chats: %w", err)
|
||||
}
|
||||
chats := make([]model.Chat, 0, limit+1)
|
||||
for rows.Next() {
|
||||
var c model.Chat
|
||||
if err := rows.Scan(&c.ID, &c.Title, &c.CreatedAt); err != nil {
|
||||
rows.Close()
|
||||
return nil, false, err
|
||||
}
|
||||
chats = append(chats, c)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
rows.Close()
|
||||
return nil, false, err
|
||||
}
|
||||
rows.Close()
|
||||
more := len(chats) > limit
|
||||
if more {
|
||||
chats = chats[:limit]
|
||||
}
|
||||
for i := range chats {
|
||||
members, err := s.getMemberIDs(ctx, chats[i].ID)
|
||||
if err != nil {
|
||||
return nil, false, err
|
||||
}
|
||||
chats[i].MemberIDs = members
|
||||
}
|
||||
return chats, more, nil
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user