public static ProductFullRequest MapToFullRequest(this UpdateProductModel model) { if (model is null) { throw new ArgumentNullException(nameof(model)); } var productRequest = new ProductFullRequest { Id = model.Id, ShortDescription = model.ShortDescription, LongDescription = model.LongDescription }; if (model.Image != null) { using var ms = new MemoryStream(); model.Image.CopyTo(ms); var fileBytes = ms.ToArray(); productRequest.Image = fileBytes; } else { productRequest.Image = Convert.FromBase64String(Constants.Defaults.Image); } foreach (var item in model.Categories) { productRequest.Categories.Add(new CategoryFullRequest { Id = item }); } return(productRequest); }
public async Task <IActionResult> UpdateProduct([FromBody] ProductFullRequest productRequest) { if (productRequest is null) { return(UnprocessableEntity(Constants.ErrorMessages.UnprocessableEntity)); } var descriptionErrorMessage = VerifyProductDescription(productRequest.ShortDescription, productRequest.LongDescription); if (!string.IsNullOrWhiteSpace(descriptionErrorMessage)) { return(BadRequest(descriptionErrorMessage)); } Product product = await _context.Products.SingleOrDefaultAsync(p => p.Id == productRequest.Id); if (product is null) { return(NotFound(Constants.ErrorMessages.NotFound)); } bool parsed = int.TryParse(User.Identity.Name, out int userId); if (!parsed) { throw new ApplicationException(Constants.ErrorMessages.UnreachableUserId); } if (product.OwnerId != userId || product.OwnerId == default) { return(Forbid(Constants.ErrorMessages.ThisUserIsNotAllowed)); } product.ShortDescription = productRequest.ShortDescription; product.LongDescription = productRequest.LongDescription; product.Image = productRequest.Image.ToArray(); if (productRequest.Categories != null && productRequest.Categories.Any()) { var categories = _context.ProductCategories.Where(p => p.ProductId == product.Id).ToList(); _context.ProductCategories.RemoveRange(categories); foreach (var categ in productRequest.Categories) { var pc = new ProductCategory { Product = product, CategoryId = categ.Id }; product.ProductCategories.Add(pc); } } var entry = _context.Products.Update(product); try { await _context.SaveChangesAsync().ConfigureAwait(false); } catch (Exception) { return(this.InternalServerError()); } var response = entry.Entity.MapToResponse(); return(Ok(response)); }