Files
components/LiteCharms.Features/Shop/Orders/Queries/Handlers/GetOrdersQueryHandler.cs
T
2026-05-13 20:06:24 +02:00

35 lines
1.3 KiB
C#

using LiteCharms.Extensions;
using LiteCharms.Features.Shop.Orders.Models;
using LiteCharms.Features.Shop.Postgres;
namespace LiteCharms.Features.Orders.Queries.Handlers;
public class GetOrdersQueryHandler(IDbContextFactory<ShopDbContext> contextFactory) : IRequestHandler<GetOrdersQuery, Result<Order[]>>
{
public async ValueTask<Result<Order[]>> Handle(GetOrdersQuery request, CancellationToken cancellationToken)
{
try
{
var fromDate = request.From.ToDateTime(TimeOnly.MinValue);
var toDate = request.To.ToDateTime(TimeOnly.MaxValue);
using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
var orders = await context.Orders
.AsNoTracking()
.OrderByDescending(o => o.CreatedAt)
.Where(o => o.CreatedAt >= fromDate && o.CreatedAt <= toDate)
.Take(request.MaxRecords)
.ToArrayAsync(cancellationToken);
return orders?.Length > 0
? Result.Ok(orders.Select(o => o.ToModel()).ToArray())
: Result.Fail<Order[]>(new Error($"No orders found for the specified date range {request.From} - {request.To}."));
}
catch (Exception ex)
{
return Result.Fail<Order[]>(new Error(ex.Message).CausedBy(ex));
}
}
}