public async Task <IResponse> CreateProductAsync(ProductRequestVm productRequest) { var product = productRequest.MapToEntity(); string storagePath = GetStoragePath(); var json = default(string); // if file not exist try { json = File.ReadAllText(storagePath); } catch (Exception) { File.WriteAllText(storagePath, String.Empty); } json = File.ReadAllText(storagePath); var products = await Task.Run(() => JsonConvert.DeserializeObject <List <Product> >(json)); var lastProductId = default(long); if (products == null) { products = new List <Product>(); lastProductId = 1; product.Id = lastProductId; if (!await _nameValidator.ValidateAsync(product.Name) | !await _descriptionValidator.ValidateAsync(product.Description)) { return(new ResponseBad <string>(400, GetErrorMsg(product))); } products.Add(product); } else { lastProductId = products.OrderByDescending(p => p.Id).FirstOrDefault().Id; lastProductId++; product.Id = lastProductId; if (!await _nameValidator.ValidateAsync(product.Name) | !await _descriptionValidator.ValidateAsync(product.Description)) { return(new ResponseBad <string>(400, GetErrorMsg(product))); } products.Add(product); } File.WriteAllText(storagePath, JsonConvert.SerializeObject(products)); return(new ResponseOk <ProductResponseVm>(201, product.MapToResponseVm())); }
public static Product MapToEntity(this ProductRequestVm productRequest) { return(productRequest == null ? null : new Product { Name = productRequest.Name, Description = productRequest.Description }); }