GetStorageLocationQueryHandler.cs 1.86 KB
using AutoMapper;
using MassTransit;
using Microsoft.Extensions.Logging;
using Rcs.Application.Common;
using Rcs.Application.DTOs;
using Rcs.Application.MessageBus.Commands.StorageLocations;
using Rcs.Domain.Repositories;

namespace Rcs.Infrastructure.MessageBus.Handlers.Commands.StorageLocations
{
    /// <summary>
    /// Get storage location detail query handler.
    /// </summary>
    public class GetStorageLocationQueryHandler : IConsumer<GetStorageLocationQuery>
    {
        private readonly ILogger<GetStorageLocationQueryHandler> _logger;
        private readonly IStorageLocationRepository _repository;
        private readonly IMapper _mapper;

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

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

            try
            {
                var entity = await _repository.GetByIdAsync(query.LocationId, context.CancellationToken);
                if (entity == null)
                {
                    await context.RespondAsync(ApiResponse<StorageLocationDto>.Failed($"Storage location not found: {query.LocationId}"));
                    return;
                }

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