Skip to content

Instantly share code, notes, and snippets.

@dcomartin
Created September 16, 2020 22:21
Show Gist options
  • Save dcomartin/7a733190b8b61458b2d66bd15f319571 to your computer and use it in GitHub Desktop.
Save dcomartin/7a733190b8b61458b2d66bd15f319571 to your computer and use it in GitHub Desktop.
using System;
using System.Security.Claims;
using System.Threading;
using System.Threading.Tasks;
using DotNetCore.CAP;
using MediatR;
using MediatR.Pipeline;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
namespace Sales
{
public class OrdersMediatRController : Controller
{
private readonly IMediator _mediator;
public OrdersMediatRController(IMediator mediator)
{
_mediator = mediator;
}
[HttpPost("/sales/orders/{orderId:Guid}")]
public async Task<IActionResult> PlaceOrder(Guid orderId, CancellationToken cancellationToken)
{
var request = new PlaceOrder
{
CustomerId = Guid.Parse(User.FindFirstValue(ClaimTypes.NameIdentifier)),
OrderId = orderId,
};
await _mediator.Send(request, cancellationToken);
return NoContent();
}
}
public class PlaceOrder : IRequest
{
public Guid CustomerId { get; set; }
public Guid OrderId { get; set; }
}
public class PlaceOrderHandler : IRequestHandler<PlaceOrder>, ICapSubscribe
{
private readonly SalesDbContext _dbContext;
public PlaceOrderHandler(SalesDbContext dbContext)
{
_dbContext = dbContext;
}
public async Task<Unit> Handle(PlaceOrder request, CancellationToken cancellationToken)
{
var order = await _dbContext.Orders
.SingleOrDefaultAsync(x =>
x.CustomerId == request.CustomerId &&
x.OrderId == request.OrderId, cancellationToken);
if (order == null)
{
throw new InvalidOperationException();
}
order.Status = OrderStatus.Placed;
await _dbContext.SaveChangesAsync(cancellationToken);
return Unit.Value;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment