fixed controllers
This commit is contained in:
@@ -1,16 +1,19 @@
|
||||
package com.krylov.refound.service;
|
||||
|
||||
import com.krylov.refound.dto.PostResponse;
|
||||
import com.krylov.refound.entity.Favorite;
|
||||
import com.krylov.refound.entity.Post;
|
||||
import com.krylov.refound.entity.User;
|
||||
import com.krylov.refound.enums.ErrorCode;
|
||||
import com.krylov.refound.exception.ApiException;
|
||||
import com.krylov.refound.mapper.PostMapper;
|
||||
import com.krylov.refound.repository.FavoriteRepository;
|
||||
import com.krylov.refound.repository.PostRepository;
|
||||
import java.util.List;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
@@ -18,44 +21,19 @@ public class FavoriteService {
|
||||
private final FavoriteRepository repository;
|
||||
private final PostRepository postRepository;
|
||||
private final UserService userService;
|
||||
private final PostMapper mapper;
|
||||
|
||||
public void addToFavorites(Long postId) {
|
||||
|
||||
@Transactional(readOnly = true)
|
||||
public List<PostResponse> getFavorites() {
|
||||
User user = userService.getCurrentUser();
|
||||
|
||||
Post post = postRepository.findById(postId)
|
||||
.orElseThrow(() -> new ApiException(ErrorCode.NOT_FOUND, "Post not found", HttpStatus.NOT_FOUND));
|
||||
|
||||
if (repository.existsByUserAndPost(user, post)) {
|
||||
return; // уже есть
|
||||
}
|
||||
|
||||
Favorite favorite = new Favorite();
|
||||
favorite.setUser(user);
|
||||
favorite.setPost(post);
|
||||
|
||||
repository.save(favorite);
|
||||
}
|
||||
|
||||
public void removeFromFavorites(Long postId) {
|
||||
|
||||
User user = userService.getCurrentUser();
|
||||
|
||||
Post post = postRepository.findById(postId)
|
||||
.orElseThrow(() -> new ApiException(ErrorCode.NOT_FOUND, "Post not found", HttpStatus.NOT_FOUND));
|
||||
|
||||
repository.deleteByUserAndPost(user, post);
|
||||
}
|
||||
|
||||
public List<Post> getFavorites() {
|
||||
User user = userService.getCurrentUser();
|
||||
|
||||
return repository.findByUser(user)
|
||||
.stream()
|
||||
.map(Favorite::getPost)
|
||||
.map(mapper::toResponse)
|
||||
.toList();
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public void toggle(Long postId) {
|
||||
|
||||
User user = userService.getCurrentUser();
|
||||
|
||||
Reference in New Issue
Block a user