build-flow.api/src/modules/rag/Application/Chat/Handlers/GetConversationDetailQueryHandler.cs
xiangning 17b7e9996e chore(dependencies): 移除未使用的 using 语句
- 从多个文件中移除未使用的 System.Linq.Dynamic.Core 引用
- 从多个文件中移除未使用的 Microsoft.EntityFrameworkCore 引用
- 从 IM 模块中移除未使用的 MongoDB.Driver.Linq 引用
- 清理 Handler 文件中的冗余命名空间引用
- 优化代码结构减少不必要的依赖引入
- 提高代码整洁性和编译效率
2026-07-02 14:53:56 +08:00

45 lines
1.9 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using MediatR;
using BuildFlow.Application.Chat.DTOs;
using BuildFlow.Shared.Domain.Exceptions;
using BuildFlow.Domain.Interfaces;
using BuildFlow.Infrastructure.Persistence;
using BuildFlow.Application.Chat.Queries;
namespace BuildFlow.Application.Chat.Handlers;
/// <summary>
/// Get会话Detail查询处理器。执行业务校验后持久化。
/// </summary>
public class GetConversationDetailQueryHandler(RagDbContext db, IChatMessageCache cache)
: IRequestHandler<GetConversationDetailQuery, ConversationDetailDto>
{
public async Task<ConversationDetailDto> Handle(GetConversationDetailQuery request, CancellationToken ct)
{
var conversation = await db.Conversations.FindAsync([request.Id], ct)
?? throw new NotFoundException("会话不存在");
// 先查 Redis 缓存
var cached = await cache.GetMessagesAsync(request.Id, ct);
if (cached is not null)
{
var messages = cached.Select(m => new ChatMessageDto(m.Id, m.Role, m.Content, m.TokenUsage, m.CreatedAt)).ToList();
return new ConversationDetailDto(conversation.Id, conversation.Title, conversation.UserId,
conversation.KnowledgeBaseId, conversation.CreatedAt, messages);
}
// 缓存 miss,查数据库
var dbMessages = await db.ChatMessages
.Where(m => m.ConversationId == request.Id)
.OrderBy(m => m.CreatedAt)
.Select(m => new ChatMessageDto(m.Id, m.Role.ToString(), m.Content, m.TokenUsage, m.CreatedAt))
.ToListAsync(ct);
// 回填 Redis
var cachedMessages = dbMessages.Select(m => new CachedChatMessage(m.Id, m.Role, m.Content, m.TokenUsage, m.CreatedAt)).ToList();
await cache.SetMessagesAsync(request.Id, cachedMessages, ct);
return new ConversationDetailDto(conversation.Id, conversation.Title, conversation.UserId,
conversation.KnowledgeBaseId, conversation.CreatedAt, dbMessages);
}
}