Esempio n. 1
0
        public async Task <int> Handle(AddNewProductCommand request, CancellationToken cancellationToken)
        {
            //validation
            var validator                        = new AddNewProductCommandValidator();
            ValidationResult results             = validator.Validate(request);
            bool             validationSucceeded = results.IsValid;

            if (!validationSucceeded)
            {
                var failures = results.Errors.ToList();
                var message  = new StringBuilder();
                failures.ForEach(f => { message.Append(f.ErrorMessage + Environment.NewLine); });
                throw new ValidationException(message.ToString());
            }
            //add new product
            var product = new Product
            {
                Id           = request.Id,
                Name         = request.Name,
                Description  = request.Description,
                UnitPrice    = 0,
                CurrentStock = 0
            };

            _context.Products.Add(product);
            await _context.SaveChangesAsync(cancellationToken);

            //notification
            await _mediator.Publish(new ProductCreated(product));

            return(1);
        }
Esempio n. 2
0
        public async Task <Unit> Handle(DeleteProductCommand request, CancellationToken cancellationToken)
        {
            var product = await _context.Products.FindAsync(request.Id);

            if (product == null)
            {
                throw new NotFoundException(nameof(Product), request.Id);
            }

            _context.Products.Remove(product);

            await _context.SaveChangesAsync(cancellationToken);

            //notification
            await _mediator.Publish(new ProductDeleted(product));

            return(Unit.Value);
        }
        public async Task <Unit> Handle(UpdateProductCurrentStockCommand request, CancellationToken cancellationToken)
        {
            var product = await _context.Products.FindAsync(request.Id);

            if (product == null)
            {
                throw new NotFoundException(nameof(Product), request.Id);
            }

            var oldStockt = product.CurrentStock;

            product.CurrentStock = request.CurrentStock;
            await _context.SaveChangesAsync(cancellationToken);

            //notification
            await _mediator.Publish(new ProductCurrentStockUpdated(product, oldStockt));


            return(Unit.Value);
        }