예제 #1
0
        public async Task <IActionResult> EditProduct([FromRoute] int id, [FromBody] ProductCreateEditRequest updatedProductData, CancellationToken cancellationToken)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var originalProduct = await _mediator.Send(new GetProductByIdRequest(id), cancellationToken);

            if (originalProduct == null)
            {
                return(NotFound());
            }

            var productsWithTheSameName = await _mediator.Send(new GetProductsByExactNameRequest(updatedProductData.Name), cancellationToken);

            var productHasChanges   = originalProduct.Name != updatedProductData.Name;
            var productCanBeUpdated = !productHasChanges || (productHasChanges && !productsWithTheSameName.Any());

            if (!productCanBeUpdated)
            {
                ModelState.AddModelError(nameof(updatedProductData.Name), $"Product with the name '{updatedProductData.Name}' already exists");
                return(BadRequest(ModelState));
            }

            originalProduct = _mapper.Map(updatedProductData, originalProduct);
            await _mediator.Send(new EditProductRequest(originalProduct), cancellationToken);

            return(Ok());
        }
예제 #2
0
        public async Task <IActionResult> CreateProduct([FromBody] ProductCreateEditRequest productData, CancellationToken cancellationToken)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var productsWithTheSameName = await _mediator.Send(new GetProductsByExactNameRequest(productData.Name), cancellationToken);

            if (productsWithTheSameName.Any())
            {
                ModelState.AddModelError(nameof(productData.Name), $"Product with the name '{productData.Name}' already exists");
                return(BadRequest(ModelState));
            }

            var product = _mapper.Map <Product>(productData);
            await _mediator.Send(new CreateProductRequest(product), cancellationToken);

            return(Ok());
        }