34 lines
1.4 KiB
C#
34 lines
1.4 KiB
C#
using LiteCharms.Extensions;
|
|
using LiteCharms.Features.Shop.Notifications.Models;
|
|
using LiteCharms.Features.Shop.Postgres;
|
|
|
|
namespace LiteCharms.Features.Notifications.Queries.Handlers;
|
|
|
|
public class GetNotificationsQueryHandler(IDbContextFactory<ShopDbContext> contextFactory) : IRequestHandler<GetNotificationsQuery, Result<Notification[]>>
|
|
{
|
|
public async ValueTask<Result<Notification[]>> Handle(GetNotificationsQuery 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 notifications = await context.Notifications.AsNoTracking()
|
|
.Where(n => n.CreatedAt >= fromDate && n.CreatedAt <= toDate)
|
|
.OrderByDescending(n => n.CreatedAt)
|
|
.Take(request.MaxRecords)
|
|
.ToArrayAsync(cancellationToken);
|
|
|
|
return notifications?.Length > 0
|
|
? Result.Ok(notifications.Select(n => n.ToModel()).ToArray())
|
|
: Result.Fail(new Error($"No notifications found for the specified date range {request.From} to {request.To}."));
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
return Result.Fail(new Error(ex.Message).CausedBy(ex));
|
|
}
|
|
}
|
|
}
|