Controller
@PostMapping("/like")
public String like(@RequestBody LikeRequestDto likeRequestDto) {
likeService.likeBoard(likeRequestDto);
return "redirect:/post/";
}
- userId와 postId를 받아서 작업을 수행함
- return은 redirect 사용
LikeRequestDto는 다음과 같다.
@Getter
@NoArgsConstructor
public class LikeRequestDto {
private Long userId;
private Long postId;
public LikeRequestDto(Long userId, Long postId) {
this.userId = userId;
this.postId = postId;
}
}
Service
@Service
@RequiredArgsConstructor
public class LikeService {
private final LikeRepository likeRepository;
private final UserRepository userRepository;
private final PostRepository postRepository;
// @Transactional
public void likeBoard(LikeRequestDto likeRequestDTO) {
User user = userRepository.findById(likeRequestDTO.getUserId())
.orElseThrow(() -> new NullPointerException("Could not found user id"));
/**
* spring security 구현이 완료되면 밑에 주석 처리된 코드로 변경하면 인증된 토큰으로 user를 판단할 수 있을 것 같음
* 아직은 구현이 안되어 있으므로 위에 있는 코드 사용
*/
// Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
// User user = userRepository.findByUsername(authentication.getName());
PostEntity post = postRepository.findById(likeRequestDTO.getPostId())
.orElseThrow(() -> new NullPointerException("Could not found board id"));
// 이미 해당 게시글에 좋아요를 누른 아이디인지 체크
if (likeRepository.findByUserAndPostEntity(user, post) != null){
Like like = likeRepository.findByUserAndPostEntity(user,post);
likeRepository.delete(like);
Long likeCount = (long)likeRepository.findByPostEntityId(post.getId()).size();
post.setLikeCount(likeCount);
} else {
Like like = new Like();
like.setPostEntity(post);
like.setUser(user);
likeRepository.save(like);
Long likeCount = (long)likeRepository.findByPostEntityId(post.getId()).size();
post.setLikeCount(likeCount);
}
}
}
- 우선 유효한 user, post인지 검증한 뒤
- 해당 user가 이미 post에 좋아요를 눌렀으면 좋아요를 취소하고 누르지 않았다면 좋아요를 누르는 기능
spring은 .. 아직 많이 어려운 것 같다.
더 소통하고 더 노력하자..
'TIL&WIL' 카테고리의 다른 글
| 2023-07-11 TIL (연관 관계) (0) | 2023.07.11 |
|---|---|
| 2023-07-07 TIL (뉴스피드 프로젝트 kpt) (0) | 2023.07.07 |
| 2023-07-04 TIL (Command Acceptance Exception) (0) | 2023.07.04 |
| 2023-07-03 TIL (정규식 활용) (0) | 2023.07.03 |
| 2023-06 마지막 주 WIL (0) | 2023.07.02 |