GetRobotsQueryHandler.cs 1.73 KB
using AutoMapper;
using MassTransit;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using Rcs.Application.Common;
using Rcs.Application.DTOs;
using Rcs.Application.MessageBus.Commands;
using Rcs.Domain.Entities;
using Rcs.Domain.Repositories;

namespace Rcs.Infrastructure.MessageBus.Handlers.Commands;

/// <summary>
/// 查询机器人列表命令处理器
/// @author zzy - 添加Include导航属性
/// </summary>
public class GetRobotsQueryHandler : IConsumer<GetRobotsQuery>
{
    private readonly ILogger<GetRobotsQueryHandler> _logger;
    private readonly IRobotRepository _robotRepository;
    private readonly IMapper _mapper;

    public GetRobotsQueryHandler(
        ILogger<GetRobotsQueryHandler> logger,
        IRobotRepository robotRepository,
        IMapper mapper)
    {
        _logger = logger;
        _robotRepository = robotRepository;
        _mapper = mapper;
    }

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

        var queryable = _robotRepository.GetQueryable();

        if (!string.IsNullOrWhiteSpace(query.FilterModel))
        {
            queryable = FilterHelper.ApplyFilters(queryable, query.FilterModel);
        }

        var totalCount = await queryable.CountAsync(context.CancellationToken);

        var robots = await queryable
            .OrderBy(m => m.RobotCode)
            .Skip((query.PageNumber - 1) * query.PageSize)
            .Take(query.PageSize)
            .ToListAsync(context.CancellationToken);

        var robotDtos = _mapper.Map<List<RobotListItemDto>>(robots);
        await context.RespondAsync(PagedResponse<RobotListItemDto>.Successful(robotDtos, query.PageNumber, query.PageSize, totalCount));
    }
}