GetMapQueryHandler.cs 1.54 KB
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;
using Rcs.Application.Dtos;

namespace Rcs.Infrastructure.MessageBus.Handlers.Commands;

/// <summary>
/// 查询单个机器人命令处理器
/// </summary>
public class GetMapQueryHandler : IConsumer<GetMapQuery>
{
    private readonly ILogger<GetMapQueryHandler> _logger;
    private readonly IMapRepository _mapRepository;
    private readonly IMapper _mapper;

    public GetMapQueryHandler(
        ILogger<GetMapQueryHandler> logger,
        IMapRepository mapRepository,
        IMapper mapper)
    {
        _logger = logger;
        _mapRepository = mapRepository;
        _mapper = mapper;
    }

    public async Task Consume(ConsumeContext<GetMapQuery> context)
    {
        var query = context.Message;
        try
        {
            var map = await _mapRepository.GetByIdAsync(
                    query.MapId, 
                    context.CancellationToken);

            if (map == null)
            {
                throw new BusinessException("地图不存在");
            }

            var mapDto = _mapper.Map<MapDto>(map);

            // 响应查询结果
            await context.RespondAsync(ApiResponse<MapDto>.Successful(mapDto));
        }
        catch (Exception ex)
        {
           await context.RespondAsync(ApiResponse<MapDto>.Failed(ex.Message));
        }
    }
}