Skip to content

Instantly share code, notes, and snippets.

@dcomartin

dcomartin/vsa.cs Secret

Created September 1, 2021 21:44
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save dcomartin/034a2091759bbdf58cc5d3a47be68fa1 to your computer and use it in GitHub Desktop.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using MediatR;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.eShopWeb.Infrastructure.Data;
namespace Microsoft.eShopWeb.Features.Orders
{
[Route("order/my-orders")]
public class GetMyOrdersController : Controller
{
private readonly IMediator _mediator;
public GetMyOrdersController(IMediator mediator)
{
_mediator = mediator;
}
[HttpGet]
public async Task<IActionResult> MyOrders()
{
var viewModel = await _mediator.Send(new GetMyOrdersQuery(User.Identity.Name));
return View("/Features/Orders/GetMyOrders.cshtml", viewModel);
}
}
public class GetMyOrdersViewModel
{
public IEnumerable<OrderSummaryViewModel> Orders { get; set; }
}
public class OrderSummaryViewModel
{
private const string DEFAULT_STATUS = "Pending";
public int OrderNumber { get; set; }
public DateTimeOffset OrderDate { get; set; }
public decimal Total { get; set; }
public string Status => DEFAULT_STATUS;
}
public class GetMyOrdersQuery : IRequest<GetMyOrdersViewModel>
{
public string UserName { get; set; }
public GetMyOrdersQuery(string userName)
{
UserName = userName;
}
}
public class GetMyOrdersHandler : IRequestHandler<GetMyOrdersQuery, GetMyOrdersViewModel>
{
private readonly CatalogContext _db;
public GetMyOrdersHandler(CatalogContext db)
{
_db = db;
}
public async Task<GetMyOrdersViewModel> Handle(GetMyOrdersQuery request, CancellationToken cancellationToken)
{
var result = new GetMyOrdersViewModel();
result.Orders = await _db.Orders
.Include(x => x.OrderItems)
.Where(x => x.BuyerId == request.UserName)
.Select(o => new OrderSummaryViewModel
{
OrderDate = o.OrderDate,
OrderNumber = o.Id,
Total = o.OrderItems.Sum(x => x.Units * x.UnitPrice),
})
.ToArrayAsync(cancellationToken);
return result;
}
}
}
@davepcallan
Copy link

davepcallan commented Jan 29, 2024

Hi @dcomartin I refactored this a bit. What do you think?

  1. File scoped namespaces to reduce indentation (and save one line)
  2. Primary constructor for controller to remove a bit of boilerplate
  3. Removed .Include on #69 as not need for projections
  4. Switch VMs to records for more concise syntax
  5. Remove MediatR as not really adding value in this context.
  6. Qualified the namespace a bit more in case of naming conflicts.

image

https://gist.github.com/davepcallan/68b6b6c54bc951309b8639fbd96caf05

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment