Skip to content

Instantly share code, notes, and snippets.

@dcomartin
Created October 26, 2023 19:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dcomartin/3dd415a448e271c115f1466079a5f5e2 to your computer and use it in GitHub Desktop.
Save dcomartin/3dd415a448e271c115f1466079a5f5e2 to your computer and use it in GitHub Desktop.
public interface IOrderReadService
{
Task<Option<OrderResponse>> GetOrderByIdAsync(int orderId);
}
public class OrderReadService : IOrderReadService
{
private readonly OrderContext _context;
public OrderReadService(OrderContext context)
{
_context = context;
}
public async Task<Option<OrderResponse>> GetOrderByIdAsync(int orderId)
{
var orderResponse = await _context.Orders
.Where(x => x.OrderId == orderId)
.Select(x => new OrderResponse
{
OrderDate = x.OrderDate,
OrderItems = x.OrderItems.Select(oi => new OrderItemResponse
{
PictureUrl = oi.PictureUrl,
ProductId = oi.ProductId,
ProductName = oi.ProductName,
UnitPrice = oi.UnitPrice,
Units = oi.Units
}).ToList(),
OrderNumber = x.OrderNumber,
ShippingAddress = x.ShippingAddress,
Total = x.Total()
})
.SingleOrDefaultAsync();
return orderResponse is null
? Option.None<OrderResponse>()
: orderResponse.Some();
}
}
public class GetOrderQueryHandler : IRequestHandler<GetOrderQuery, Option<OrderResponse>>
{
private readonly IOrderReadService _orderReadService;
public GetOrderQueryHandler(IOrderReadService orderReadService)
{
_orderReadService = orderReadService;
}
public Task<Option<OrderResponse>> Handle(GetOrderQuery request, CancellationToken cancellationToken)
{
return _orderReadService.GetOrderByIdAsync(request.OrderId);
}
}
public class OrderController : Controller
{
private readonly IMediator _mediator;
public OrderController(IMediator mediator)
{
_mediator = mediator;
}
public async Task<IActionResult> Detail(int orderId)
{
var viewModel = await _mediator.Send(new GetOrderQuery(orderId));
return viewModel.Match(
some: result => View(result),
none: () => NotFound($"Order ({orderId}) not found."));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment