28 lines
950 B
C#
28 lines
950 B
C#
using LiteCharms.Extensions;
|
|
using LiteCharms.Infrastructure.Database;
|
|
using LiteCharms.Models;
|
|
|
|
namespace LiteCharms.Features.Products.Queries.Handlers;
|
|
|
|
public class GetProductsQueryHandler(IDbContextFactory<LeadGeneratorDbContext> contextFactory) : IRequestHandler<GetProductsQuery, Result<Product[]>>
|
|
{
|
|
public async ValueTask<Result<Product[]>> Handle(GetProductsQuery request, CancellationToken cancellationToken)
|
|
{
|
|
try
|
|
{
|
|
using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
|
|
|
|
var products = await context.Products.AsNoTracking()
|
|
.OrderByDescending(o => o.Id)
|
|
.Take(request.MaxRecords)
|
|
.ToArrayAsync(cancellationToken);
|
|
|
|
return Result.Ok(products.Select(p => p.ToModel()).ToArray());
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
return Result.Fail<Product[]>(new Error(ex.Message).CausedBy(ex));
|
|
}
|
|
}
|
|
}
|