관리 메뉴

개발하는 동그리

[Main Project] 게시글 좋아요 구현 본문

스테이츠 코드(백엔드)/Main Project

[Main Project] 게시글 좋아요 구현

개발하는 동그리 2022. 9. 29. 15:43
반응형

좋아요 설정에 필요한 클래스 

  • LikesController
  • LikesEntity
  • LikesService
  • LikesRepository

 

LikesController Class

@RestController
@RequestMapping("/v1")
@Slf4j
@RequiredArgsConstructor
public class LikesController {
    private final LikesService likeService;

    @PostMapping("/likes/{posts-id}")
    public ResponseEntity addLike(@PathVariable("posts-id") Long postsId
            , @AuthenticationPrincipal PrincipalDetails principal) {

        log.info("===================좋아요 클릭=======================");
        boolean result = false;

        if (principal != null) {
            result = likeService.booleanLike(principal.getUsers().getId(), postsId);
        }

        return result ?
                new ResponseEntity<>("좋아요 추가", HttpStatus.OK) :
                new ResponseEntity<>("좋아요 삭제", HttpStatus.BAD_REQUEST);
    }
}

 

LikesEntity Class

@Entity
@NoArgsConstructor
@AllArgsConstructor
@Getter
public class Likes {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private Long usersId;

    private Long postsId;

    public Likes(Long usersId, Long postsId) {
        this.usersId = usersId;
        this.postsId = postsId;
    }
}

 

LikesService Class

@Transactional
@RequiredArgsConstructor
@Service
public class LikesService {

    private final LikesRepository likeRepository;
    private final PostsService postsService;

    public boolean booleanLike(Long usersId, Long postsId) {


        Posts posts = postsService.findById(postsId);

        if (isNotAlreadyLike(usersId, postsId)) {
            posts.setLikesCount(posts.getLikesCount() + 1);
            likeRepository.save(new Likes(usersId, postsId));
            postsService.savedLikesCount(posts);
            return true;

        } else {
            posts.setLikesCount(posts.getLikesCount() - 1);
            likeRepository.delete(findLikes(usersId, postsId));
            postsService.savedLikesCount(posts);
        }
        return false;
    }

    @Transactional(readOnly = true)
    public boolean isNotAlreadyLike(Long usersId, Long postsId) {
        return likeRepository.findByUsersIdAndPostsId(usersId, postsId).isEmpty();
    }

    @Transactional(readOnly = true)
    public boolean isAlreadyLike(long likesId) {
        return likeRepository.findById(likesId).isPresent();
    }

    @Transactional(readOnly = true)
    public Likes findLikes(Long usersId, Long postsId) {
        return likeRepository.findByUsersIdAndPostsId(usersId, postsId).orElse(null);
    }
}

 

LikesRepository

public interface LikesRepository extends JpaRepository<Likes, Long> {
    Optional<Likes> findByUsersIdAndPostsId(Long usersId, Long PostsId);

}

 

반응형