public async Task <CartModel> Handle(AddBookToCartCommand request, CancellationToken cancellationToken) { var book = await _dbContext.Books.SingleOrDefaultAsync( x => x.Id == request.BookId, cancellationToken); if (book == null) { throw NotFoundError.CreateForResource(nameof(Book), request.BookId).ToException(); } Cart cart = null; if (request.CartId != null) { cart = await _dbContext.Carts.Include(x => x.Books).SingleOrDefaultAsync( x => x.Id == request.CartId.Value, cancellationToken); } if (cart == null) { cart = new Cart(book, request.CartId); await _dbContext.Carts.AddAsync(cart, cancellationToken); } else { cart.AddBook(book); } await _dbContext.SaveChangesAsync(cancellationToken); var cartModel = _mapper.Map <CartModel>(cart); return(cartModel); }
public Task <BookModel> Handle(GetBookQuery request, CancellationToken cancellationToken) { var book = _mapper .ProjectTo <BookModel>(_dbContext.Books) .FirstOrDefaultAsync(x => x.Id == request.BookId, cancellationToken); if (book == null) { throw NotFoundError.CreateForResource(nameof(Book), request.BookId).ToException(); } return(book); }
public async Task <OrderModel> Handle(SubmitOrderCommand request, CancellationToken cancellationToken) { var cart = await _dbContext.Carts .Include(x => x.Books) .SingleOrDefaultAsync( x => x.Id == request.CartId, cancellationToken); if (cart == null) { throw NotFoundError.CreateForResource(nameof(Cart), request.CartId).ToException(); } var order = new Order(cart, request.PhoneNumber); await _dbContext.AddAsync(order, cancellationToken); _dbContext.Remove(cart); await _dbContext.SaveChangesAsync(cancellationToken); return(_mapper.Map <OrderModel>(order)); }