public async Task <ActionResult <ProductDTO> > CreateProductAsync([FromForm] ProductForCreate model) { if (!ModelState.IsValid) { var errors = ModelState.Values.SelectMany(v => v.Errors).Select(e => e.ErrorMessage).ToList(); return(BadRequest(new ErrorResponse(HttpStatusCode.BadRequest, "Validation error", errors))); } var result = await _productService.CreateProductAsync(model); return(result.Succeed ? CreatedAtRoute(nameof(GetProductByIdAsync), new { id = result.Value.Id }, result.Value) : BadRequest(new ErrorResponse(HttpStatusCode.BadRequest, "Create fail", result.Errors))); }
public async Task <ProcessResult <ProductDTO> > CreateProductAsync(ProductForCreate model) { async Task <ProductDTO> action() { if (await _repoWrapper.Category.FindById(model.CategoryId) == null) { throw new InvalidOperationException("CategoryId is not exist"); } var entity = await _repoWrapper.Product.FindProductByNameAsync(model.ProductName); if (entity != null) { throw new InvalidOperationException("ProductName is exist"); } var product = _mapper.Map <Product>(model); product.CreateBy = CurrentUser.UserName; product.CreateDate = DateTime.Now; product.Status = true; if (model.Files != null) { string error = ""; var photos = new List <ProductPhoto>(); for (int i = 0; i < model.Files.Length; i++) { var resultUpload = await _cloudDinaryService.AddAsync(model.Files[i]); if (resultUpload.Error != null) { error = resultUpload.Error.Message; break; } photos.Add(new ProductPhoto { Id = Guid.NewGuid(), PublicId = resultUpload.PublicId, Url = resultUpload.SecureUrl.AbsoluteUri, IsMain = false, CreateBy = CurrentUser.UserName, CreateDate = DateTime.UtcNow }); } if (error.Length > 0) { photos.ForEach(async x => await DeletePhotoFromCloudinary(x.PublicId)); throw new InvalidOperationException(error); } photos[0].IsMain = true; product.ProductPhotos = photos; } _repoWrapper.Product.CreateProduct(product); return(await _repoWrapper.SaveAsync() > 0 ? _mapper.Map <ProductDTO>(product) : throw new InvalidOperationException("Save fail")); } return(await Process.RunAsync(action)); }