Files
components/LiteCharms.Features/CartPackages/Commands/Handlers/CreatePackageCommandHandler.cs
T
2026-05-10 14:18:56 +02:00

33 lines
1.2 KiB
C#

using LiteCharms.Infrastructure.Database;
namespace LiteCharms.Features.CartPackages.Commands.Handlers;
public class CreatePackageCommandHandler(IDbContextFactory<ShopDbContext> contextFactory) : IRequestHandler<CreatePackageCommand, Result<Guid>>
{
public async ValueTask<Result<Guid>> Handle(CreatePackageCommand request, CancellationToken cancellationToken)
{
try
{
using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
if (await context.Packages.AnyAsync(p => p.Name == request.Name, cancellationToken))
return Result.Fail($"A package by the same name already exists: {request.Name}");
var newPackage = context.Packages.Add(new Entities.Package
{
Name = request.Name,
Description = request.Description,
Active = true
});
return await context.SaveChangesAsync(cancellationToken) > 0
? Result.Ok(newPackage.Entity.Id)
: Result.Fail($"Failed to create a new package by the name: {request.Name}");
}
catch (Exception ex)
{
return Result.Fail<Guid>(new Error(ex.Message).CausedBy(ex));
}
}
}