33 lines
1.3 KiB
C#
33 lines
1.3 KiB
C#
using LiteCharms.Extensions;
|
|
using LiteCharms.Infrastructure.Database;
|
|
using LiteCharms.Models;
|
|
|
|
namespace LiteCharms.Features.Products.Queries.Handlers;
|
|
|
|
public class GetProductPriceQueryHandler(IDbContextFactory<ShopDbContext> contextFactory) : IRequestHandler<GetProductPriceQuery, Result<ProductPrice>>
|
|
{
|
|
public async ValueTask<Result<ProductPrice>> Handle(GetProductPriceQuery request, CancellationToken cancellationToken)
|
|
{
|
|
try
|
|
{
|
|
using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
|
|
|
|
if(!await context.Products.AnyAsync(p => p.Id == request.ProductId, cancellationToken))
|
|
return Result.Fail<ProductPrice>(new Error($"Product {request.ProductId} not found."));
|
|
|
|
var productPrice = await context.ProductPrices.AsNoTracking()
|
|
.Where(pp => pp.ProductId == request.ProductId && pp.Active)
|
|
.OrderByDescending(pp => pp.CreatedAt)
|
|
.FirstOrDefaultAsync(cancellationToken);
|
|
|
|
return productPrice is not null
|
|
? Result.Ok(productPrice.ToModel())
|
|
: Result.Fail<ProductPrice>(new Error($"Product price {request.ProductId} not found."));
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
return Result.Fail<ProductPrice>(new Error(ex.Message).CausedBy(ex));
|
|
}
|
|
}
|
|
}
|