Sort chat rooms by last message created at

This commit is contained in:
LittleSheep 2025-05-24 02:12:32 +08:00
parent b905d674b7
commit 2eff4364c9
2 changed files with 19 additions and 0 deletions

View File

@ -54,6 +54,7 @@ public class ChatRoomController(
.Select(m => m.ChatRoom)
.ToListAsync();
chatRooms = await crs.LoadDirectMessageMembers(chatRooms, userId);
chatRooms = await crs.SortChatRoomByLastMessage(chatRooms);
return Ok(chatRooms);
}

View File

@ -1,6 +1,7 @@
using DysonNetwork.Sphere.Account;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Caching.Memory;
using NodaTime;
namespace DysonNetwork.Sphere.Chat;
@ -32,6 +33,23 @@ public class ChatRoomService(AppDatabase db, IMemoryCache cache)
var cacheKey = string.Format(RoomMembersCacheKey, roomId);
cache.Remove(cacheKey);
}
public async Task<List<ChatRoom>> SortChatRoomByLastMessage(List<ChatRoom> rooms)
{
var roomIds = rooms.Select(r => r.Id).ToList();
var lastMessages = await db.ChatMessages
.Where(m => roomIds.Contains(m.ChatRoomId))
.GroupBy(m => m.ChatRoomId)
.Select(g => new { RoomId = g.Key, CreatedAt = g.Max(m => m.CreatedAt) })
.ToDictionaryAsync(g => g.RoomId, m => m.CreatedAt);
var now = SystemClock.Instance.GetCurrentInstant();
var sortedRooms = rooms
.OrderByDescending(r => lastMessages.TryGetValue(r.Id, out var time) ? time : now)
.ToList();
return sortedRooms;
}
public async Task<List<ChatRoom>> LoadDirectMessageMembers(List<ChatRoom> rooms, Guid userId)
{