27 lines
972 B
C#
27 lines
972 B
C#
using LiteCharms.Extensions;
|
|
using LiteCharms.Infrastructure.Database;
|
|
using LiteCharms.Models;
|
|
|
|
namespace LiteCharms.Features.Products.Queries.Handlers;
|
|
|
|
public class GetProductQueryHandler(IDbContextFactory<LeadGeneratorDbContext> contextFactory) : IRequestHandler<GetProductQuery, Result<Product>>
|
|
{
|
|
public async ValueTask<Result<Product>> Handle(GetProductQuery request, CancellationToken cancellationToken)
|
|
{
|
|
try
|
|
{
|
|
using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
|
|
|
|
var product = await context.Products.FirstOrDefaultAsync(p => p.Id == request.ProductId, cancellationToken);
|
|
|
|
return product is not null
|
|
? Result.Ok(product.ToModel())
|
|
: Result.Fail<Product>(new Error($"Product with ID {request.ProductId} not found."));
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
return Result.Fail<Product>(new Error(ex.Message).CausedBy(ex));
|
|
}
|
|
}
|
|
}
|