예제 #1
0
        public async Task <Unit> Handle(CreateFoodCommand request, CancellationToken cancellationToken)
        {
            var entity = new Food
            {
                Name          = request.Name,
                Price         = request.Price,
                Description   = request.Description,
                Weight        = request.Weight,
                Size          = request.Size,
                Protein       = request.Protein,
                Fats          = request.Fats,
                Carbohydrates = request.Carbohydrates,
                Calories      = request.Calories,
                TypeId        = request.TypeId
            };

            if (request.Image != null)
            {
                AmazonS3 amazon = new AmazonS3();

                string filename = amazon.GetRandomFileNameWithPrefix(request.Image.FileName, 100000, 5);
                string path     = $"images/food/{filename}";

                await amazon.UploadFoodImage(request.Image, filename);

                entity.ImagePath = path;
                amazon.Dispose();
            }
            else
            {
                entity.ImagePath = "images/food/default.jpg";
            }

            await _context.Food.AddAsync(entity);

            await _context.SaveChangesAsync(cancellationToken);

            return(Unit.Value);
        }
        public async Task <Unit> Handle(UpdateFoodCommand request, CancellationToken cancellationToken)
        {
            var entity = await _context.Food.SingleOrDefaultAsync(x => x.Id == request.Id, cancellationToken);

            if (entity == null)
            {
                throw new EntityNotFoundException(nameof(Food), request.Id);
            }

            entity.Name          = request.Name;
            entity.Price         = request.Price;
            entity.Description   = request.Description;
            entity.Weight        = request.Weight;
            entity.Size          = request.Size;
            entity.Protein       = request.Protein;
            entity.Fats          = request.Fats;
            entity.Carbohydrates = request.Carbohydrates;
            entity.Calories      = request.Calories;
            entity.TypeId        = request.TypeId;

            if (request.Image != null)
            {
                AmazonS3 amazon = new AmazonS3();

                string filename = amazon.GetRandomFileNameWithPrefix(request.Image.FileName, 100000, 5);
                string path     = $"images/food/{filename}";

                await amazon.DeleteFoodImageAsync(entity.ImagePath);

                await amazon.UploadFoodImage(request.Image, filename);

                entity.ImagePath = path;
            }

            await _context.SaveChangesAsync(cancellationToken);

            return(Unit.Value);
        }