GetChargingPileQueryHandler.cs 1.8 KB
using AutoMapper;
using MassTransit;
using Microsoft.Extensions.Logging;
using Rcs.Application.Common;
using Rcs.Application.DTOs;
using Rcs.Application.MessageBus.Commands.ChargingPile;
using Rcs.Domain.Repositories;

namespace Rcs.Infrastructure.MessageBus.Handlers.Commands.ChargingPile
{
    /// <summary>
    /// Get charging pile detail query handler.
    /// </summary>
    public class GetChargingPileQueryHandler : IConsumer<GetChargingPileQuery>
    {
        private readonly ILogger<GetChargingPileQueryHandler> _logger;
        private readonly IChargingPileRepository _repository;
        private readonly IMapper _mapper;

        public GetChargingPileQueryHandler(
            ILogger<GetChargingPileQueryHandler> logger,
            IChargingPileRepository repository,
            IMapper mapper)
        {
            _logger = logger;
            _repository = repository;
            _mapper = mapper;
        }

        public async Task Consume(ConsumeContext<GetChargingPileQuery> context)
        {
            var query = context.Message;

            try
            {
                var entity = await _repository.GetByIdAsync(query.PileId, context.CancellationToken);
                if (entity == null)
                {
                    await context.RespondAsync(ApiResponse<ChargingPileDto>.Failed($"Charging pile not found: {query.PileId}"));
                    return;
                }

                var dto = _mapper.Map<ChargingPileDto>(entity);
                await context.RespondAsync(ApiResponse<ChargingPileDto>.Successful(dto));
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Get charging pile detail failed");
                await context.RespondAsync(ApiResponse<ChargingPileDto>.Failed(ex.Message));
            }
        }
    }
}