GetRobotQueryHandler.cs
1.66 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
using MassTransit;
using Microsoft.Extensions.Logging;
using Rcs.Application.DTOs;
using Rcs.Application.MessageBus.Commands;
using Rcs.Domain.Entities;
using Rcs.Domain.Repositories;
using AutoMapper;
using Rcs.Domain.Extensions;
using Rcs.Application.Common;
namespace Rcs.Infrastructure.MessageBus.Handlers.Commands;
/// <summary>
/// 查询单个机器人命令处理器
/// </summary>
public class GetRobotQueryHandler : IConsumer<GetRobotQuery>
{
private readonly ILogger<GetRobotQueryHandler> _logger;
private readonly IRobotRepository _robotRepository;
private readonly IMapper _mapper;
public GetRobotQueryHandler(
ILogger<GetRobotQueryHandler> logger,
IRobotRepository robotRepository,
IMapper mapper)
{
_logger = logger;
_robotRepository = robotRepository;
_mapper = mapper;
}
public async Task Consume(ConsumeContext<GetRobotQuery> context)
{
var query = context.Message;
try
{
var robot = await _robotRepository.GetByIdFullDataAsync(
query.RobotId,
context.CancellationToken);
if (robot == null)
{
throw new InvalidOperationException("机器人不存在");
}
// 使用AutoMapper映射到DTO(包含枚举到字符串的自动转换)
var robotDto = _mapper.Map<RobotDto>(robot);
// 响应查询结果
await context.RespondAsync(ApiResponse<RobotDto>.Successful(robotDto));
}
catch (Exception ex)
{
await context.RespondAsync(ApiResponse<RobotDto>.Failed(ex.Message));
}
}
}