Retructured solution
This commit is contained in:
@@ -0,0 +1,32 @@
|
||||
using LiteCharms.Extensions;
|
||||
using LiteCharms.Features.Shop.CartPackages.Models;
|
||||
using LiteCharms.Features.Shop.Postgres;
|
||||
|
||||
namespace LiteCharms.Features.CartPackages.Queries.Handlers;
|
||||
|
||||
public class GetPackageItemsQueryHandler(IDbContextFactory<ShopDbContext> contextFactory) : IRequestHandler<GetPackageItemsQuery, Result<PackageItem[]>>
|
||||
{
|
||||
public async ValueTask<Result<PackageItem[]>> Handle(GetPackageItemsQuery request, CancellationToken cancellationToken)
|
||||
{
|
||||
try
|
||||
{
|
||||
using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
|
||||
|
||||
if (!await context.Packages.AnyAsync(p => p.Id == request.PackageId, cancellationToken))
|
||||
return Result.Fail<PackageItem[]>($"Package could not be found with ID {request.PackageId}");
|
||||
|
||||
var items = await context.PackageItems.AsNoTracking()
|
||||
.OrderByDescending(o => o.CreatedAt)
|
||||
.Where(p => p.PackageId == request.PackageId)
|
||||
.ToArrayAsync(cancellationToken);
|
||||
|
||||
return items?.Length > 0
|
||||
? Result.Ok(items.Select(i => i.ToModel()).ToArray())
|
||||
: Result.Fail<PackageItem[]>($"Could not find package items by package ID {request.PackageId}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
return Result.Fail<PackageItem[]>(new Error(ex.Message).CausedBy(ex));
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user