Ejemplo n.º 1
0
        public async Task <CreateFavorite.Response> AddToFavorite(CreateFavorite.Request request, CancellationToken cancellationToken)
        {
            var userId = await _identityService.GetCurrentUserId(cancellationToken);

            if (string.IsNullOrEmpty(userId))
            {
                throw new UserNotFoundException("Пользователь не найден");
            }

            var advertisement = await _advertisementRepository.FindById(request.AdvertisementId, cancellationToken);

            if (advertisement == null)
            {
                throw new AdvertisementNotFoundException($"Объявление с Id = {request.AdvertisementId} не было найдено");
            }

            var advertisementInFavoriteCurrentUser = await _repository.FindWhere(a => a.UserId == userId && a.AdvertisementId == request.AdvertisementId, cancellationToken);

            if (advertisementInFavoriteCurrentUser != null)
            {
                throw new DuplicateFavoriteException($"Объявление с id = {request.AdvertisementId} уже содержится в избранных пользователя");
            }

            var favorite = new Domain.Favorite
            {
                AdvertisementId = advertisement.Id,
                UserId          = userId,
                CreatedDate     = DateTime.UtcNow
            };

            await _repository.Save(favorite, cancellationToken);

            return(new CreateFavorite.Response
            {
                Id = favorite.Id
            });
        }