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);
        }
예제 #2
0
        public int GetRoadCurrentStatus(string road)
        {
            try
            {
                var roadStatus = restClient.Get(road);

                if (!string.IsNullOrEmpty(roadStatus?.Trim()))
                {
                    if (restClient.StatusCode == HttpStatusCode.OK)
                    {
                        CorridorStatus = JsonConvert.DeserializeObject <CorridorStatus[]>(roadStatus)?.First();
                        PrintStatus();

                        return(0);
                    }
                    else if (restClient.StatusCode == HttpStatusCode.NotFound)
                    {
                        HttpNotFoundError = JsonConvert.DeserializeObject <NotFoundError>(roadStatus);
                        PrintError(road);

                        return(1);
                    }
                }
            }
            catch (Exception) { /* Implement Logging if required */ }

            return(-1);
        }
 public static IActionResult ToActionResult(this DomainError error, ILogger log)
 {
     return(error switch
     {
         ExceptionError eError => eError.ToActionResult(log),
         ValidationErrors vError => vError.ToActionResult(log),
         NotFoundError nError => nError.ToActionResult(log),
         BasicError bError => bError.ToActionResult(log),
         _ => new InternalServerErrorResult()
     });
예제 #4
0
 internal static async Task <Either <DomainError, T> > TryExecute <T>(Func <Task <T> > action)
 {
     try
     {
         return(await action());
     }
     catch (Exception e)
     {
         return(e.Message == "Not Found" ?
                Left <DomainError, T>(NotFoundError.Create("TableOperation", "The entity was not found")) :
                Left <DomainError, T>(ExceptionError.FromException(e, "TableOperation")));
     }
 }
        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);
        }
예제 #6
0
        public void GetResponseFromResult_NotFoundError_ReturnsBadRequest()
        {
            // Arrange
            var controllerBase = new TestController();
            var errorMessage   = "Nie znaleziono";
            var error          = new NotFoundError(errorMessage);
            var result         = new Result(error);

            // Act
            var response = controllerBase.GetResponseFromResult(result);

            // Assert
            Assert.IsType <BadRequestObjectResult>(response);
            Assert.Equal(errorMessage, (response as BadRequestObjectResult).Value);
        }
예제 #7
0
        /// <summary>
        /// Logs message and exception if passed that caused <see cref="HttpStatusCode.NotFound"/> error. Creates and returns <see cref="NotFoundObjectResult"/>, which describes the error.
        /// </summary>
        /// <param name="exception">An exception that causes NotFoundError.</param>
        /// <param name="notFoundObject">An object that processing causes NotFoundError.</param>
        /// <returns>A <see cref="NotFoundObjectResult"/> described en NotFoundError.</returns>
        protected virtual NotFoundObjectResult OnNotFoundError(string errorMessage, Exception exception = null)
        {
            if (exception is null)
            {
                _logger.LogWarning($"{errorMessage}");
            }
            else
            {
                _logger.LogWarning(exception, $"{exception.GetType().Name} - {errorMessage}");
            }

            var error         = new NotFoundError(errorMessage);
            var errorResponse = new ResponseWrapper(error);

            return(NotFound(errorResponse));
        }
예제 #8
0
        private static ProblemDetails CreateDefaultProblemDetails(Error error)
        {
            int statusCode = error switch
            {
                UnauthorizedError _ => StatusCodes.Status403Forbidden,
                NotFoundError _ => StatusCodes.Status404NotFound,
                ConflictError _ => StatusCodes.Status409Conflict,
                _ => StatusCodes.Status400BadRequest
            };

            return(new ProblemDetails
            {
                Detail = error.Detail,
                Status = statusCode,
                Title = error.Title,
                Type = $"https://httpstatuses.com/{statusCode}"
            });
        }
    }
        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));
        }
예제 #10
0
        public static IActionResult GetResponseFromResult(this ControllerBase controllerBase, Result result)
        {
            if (result.Succeeded)
            {
                var type = result.GetType();

                if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Result <>))
                {
                    return(controllerBase.Ok(type.GetProperty("Value").GetValue(result, null)));
                }

                return(controllerBase.NoContent());
            }

            return(result.Error switch
            {
                NotFoundError e => controllerBase.BadRequest(e.Message),
                DataValidationError e => controllerBase.BadRequest(e.Message),
                AuthorizationError e => controllerBase.Forbid(e.Message),
                IdentityError e => controllerBase.BadRequest(e.Message),
                BuisnessRuleViolationError e => controllerBase.BadRequest(e.Message),
                _ => throw new UnhandledErrorResultException() //TODO: Error message
            });
예제 #11
0
        public Response NotFoundError(string id)
        {
            var error = new NotFoundError(id);

            return(new Response(error.StatusCode, error.ErrorMessage));
        }