Api/Netina.Repository/Handlers/Orders/GetUserOrdersQueryHandler.cs

50 lines
2.0 KiB
C#

using Microsoft.EntityFrameworkCore;
using Netina.Common.Models.Api;
using Netina.Common.Models.Exception;
using Netina.Domain.CommandQueries.Queries;
using Netina.Domain.Dtos.SmallDtos;
using Netina.Domain.Entities.Orders;
using Netina.Domain.Entities.Users;
using Netina.Repository.Abstracts;
using Netina.Repository.Repositories.Base.Contracts;
namespace Netina.Repository.Handlers.Orders;
public class GetUserOrdersQueryHandler : IRequestHandler<GetUserOrdersQuery, List<OrderSDto>>
{
private readonly ICurrentUserService _currentUserService;
private readonly IRepositoryWrapper _repositoryWrapper;
public GetUserOrdersQueryHandler(ICurrentUserService currentUserService,IRepositoryWrapper repositoryWrapper)
{
_currentUserService = currentUserService;
_repositoryWrapper = repositoryWrapper;
}
public async Task<List<OrderSDto>> Handle(GetUserOrdersQuery request, CancellationToken cancellationToken)
{
Guid customerId = Guid.Empty;
if (request.CustomerId == default)
{
if (_currentUserService.UserId == null)
throw new AppException("Token is wrong", ApiResultStatusCode.UnAuthorized);
if (!Guid.TryParse(_currentUserService.UserId, out Guid userId))
throw new AppException("Token is wrong", ApiResultStatusCode.UnAuthorized);
var customer = await _repositoryWrapper.SetRepository<Customer>()
.TableNoTracking
.FirstOrDefaultAsync(c => c.UserId == userId, cancellationToken);
if (customer == null)
throw new AppException("User is not a customer");
customerId = customer.Id;
}
else
customerId = request.CustomerId;
var orders = await _repositoryWrapper.SetRepository<Order>()
.TableNoTracking
.Where(o => o.CustomerId == customerId)
.Select(OrderMapper.ProjectToSDto)
.ToListAsync(cancellationToken);
return orders;
}
}