Api/Netina.Repository/Handlers/Reviews/DeleteReviewCommandHandler.cs

26 lines
1.1 KiB
C#

namespace Netina.Repository.Handlers.Reviews;
public class DeleteReviewCommandHandler(IRepositoryWrapper repositoryWrapper)
: IRequestHandler<DeleteReviewCommand, Guid>
{
public async Task<Guid> Handle(DeleteReviewCommand request, CancellationToken cancellationToken)
{
var review = await repositoryWrapper.SetRepository<Review>().TableNoTracking
.FirstOrDefaultAsync(r => r.Id == request.Id, cancellationToken);
if (review == null)
throw new AppException("Review not found", ApiResultStatusCode.NotFound);
var product = await repositoryWrapper.SetRepository<Product>()
.TableNoTracking
.FirstOrDefaultAsync(p => p.Id == review.ProductId, cancellationToken);
if (product != null)
{
product.RemoveRate(review.Rate);
repositoryWrapper.SetRepository<Product>().Update(product);
await repositoryWrapper.SaveChangesAsync(cancellationToken);
}
repositoryWrapper.SetRepository<Review>().Delete(review);
await repositoryWrapper.SaveChangesAsync(cancellationToken);
return review.Id;
}
}