Пример #1
0
        public async Task <ActionResult <object> > Post([FromBody] ProductDto req)
        {
            try
            {
                var errors = new List <string>();
                if (string.IsNullOrEmpty(req.Sku))
                {
                    errors.Add("Sku must be not null");
                }
                if (string.IsNullOrEmpty(req.Name))
                {
                    errors.Add("Name must be not null");
                }
                if (req.Price <= 0)
                {
                    errors.Add("Price must be > 0");
                }

                if (errors.Any())
                {
                    return(Ok(new ErrorResponse
                    {
                        Errors = errors
                    }));
                }

                var existed = await ProductRepo.GetBySku(req.Sku);

                if (existed != null)
                {
                    return(Ok(new ErrorResponse
                    {
                        Errors = new List <string> {
                            $"sku {req.Sku} existed"
                        }
                    }));
                }

                var idMax = await ProductRepo.GetMaxId();

                var pr = new Product
                {
                    Id           = idMax + 1,
                    Sku          = req.Sku,
                    Price        = req.Price,
                    Name         = req.Name,
                    Description  = req.Description,
                    CreatedDate  = DateTime.Now,
                    ModifiedDate = DateTime.Now
                };
                var p = await ProductRepo.AddSync(pr);

                var res = new ProductDto
                {
                    Id          = p.Id,
                    Sku         = p.Sku,
                    Name        = p.Name,
                    Price       = p.Price,
                    Description = p.Description,
                    CreatedDate = p.CreatedDate,
                    UpdatedDate = p.ModifiedDate
                };
                return(Ok(res));
            }
            catch (Exception ex)
            {
                Log.Error(ex, ex.Message);
                throw ex;
            }
        }