Ejemplo n.º 1
0
        /// <summary>Add a new beer for a specific brewery.</summary>
        /// <param name="newBeer">The new beer to add.</param>
        /// <returns>
        ///     A success result with the new beer as value.<br />
        ///     A failure result with Validation as error code if newBeer has params validation errors.<br />
        ///     A failure result with NotFound as error code if the brewery does not exist.
        /// </returns>
        public async Task <Result <Beer> > AddBeerAsync(Beer newBeer)
        {
            if (!newBeer.Is(BeerSpecifications.HasValidName))
            {
                return(Result.Failure(newBeer, ResultErrorCode.Validation, "The name should not be empty."));
            }
            if (!newBeer.Is(BeerSpecifications.HasValidStrength))
            {
                return(Result.Failure(newBeer, ResultErrorCode.Validation, "The strength should be greater or equal than zero."));
            }
            if (!newBeer.Is(BeerSpecifications.HasValidPrice))
            {
                return(Result.Failure(newBeer, ResultErrorCode.Validation, "The price should be greater than zero."));
            }
            if (!newBeer.Is(BeerSpecifications.HasValidBreweryId))
            {
                return(Result.Failure(newBeer, ResultErrorCode.Validation, "The brewery id should not be empty."));
            }

            var brewery = await _context.Breweries.FindAsync(newBeer.BreweryId);

            if (brewery == null)
            {
                return(Result.Failure(newBeer, ResultErrorCode.NotFound, $"The brewery with {newBeer.BreweryId} was not found."));
            }

            await _context.Beers.AddAsync(newBeer);

            await _context.SaveChangesAsync();

            return(Result.Success(newBeer));
        }