Exemplo n.º 1
0
        public async Task <OperationResult> CreateProductAsync(
            Product product,
            IEnumerable <Image> images,
            IEnumerable <int> categoryIds,
            IEnumerable <Description> descriptions)
        {
            ThrowIfDisposed();
            if (product == null)
            {
                throw new ArgumentNullException(nameof(product));
            }
            if (images == null)
            {
                images = Enumerable.Empty <Image>();
            }
            if (categoryIds == null)
            {
                categoryIds = Enumerable.Empty <int>();
            }
            if (descriptions == null)
            {
                descriptions = Enumerable.Empty <Description>();
            }


            var result = await Validate(new[] { product }, ProductValidators);

            if (!result.Succeeded)
            {
                return(result);
            }

            var imagesArray = images as Image[] ?? images.ToArray();

            result = await Validate(imagesArray, ImageValidators);

            if (!result.Succeeded)
            {
                return(result);
            }

            var descsArray = descriptions as Description[] ?? descriptions.ToArray();

            result = await Validate(descsArray, DescriptionValidators);

            if (!result.Succeeded)
            {
                return(result);
            }

            TransformImages(imagesArray);

            using (var tran = _repository.BeginTransaction())
            {
                result = await _repository.CreateProductAsync(product, CancellationToken);

                if (!result.Succeeded)
                {
                    return(result);
                }

                if (!categoryIds.IsNullOrEmpty())
                {
                    result = await _repository.AddProductCategoriesAsync(product.Id, categoryIds,
                                                                         CancellationToken);

                    if (!result.Succeeded)
                    {
                        return(result);
                    }
                }

                if (!descsArray.IsNullOrEmpty())
                {
                    result = await _repository.CreateProductDescriptions(product.Id, descsArray, CancellationToken);

                    if (!result.Succeeded)
                    {
                        return(result);
                    }
                }

                if (!imagesArray.IsNullOrEmpty())
                {
                    result = await _repository.CreateImagesAsync(product.Id, imagesArray, CancellationToken);

                    if (!result.Succeeded)
                    {
                        return(result);
                    }
                }

                tran.Commit();
            }

            return(OperationResult.Success());
        }