TIL 23.01.04

쓰옹·2023년 1월 4일
0

개발자를 향해~~TIL✍

목록 보기
57/87

팀프로젝트

기존 심화과제 댓글불러오는 데 문제가 있었다.

CommentService에서 댓글을 생성하고 생성한 애를 저장을 할 때

Comment comment = commentRepository.save(
												new Comment(commentRequestDto, post, requestedUsername)
);
post.addComment(comment);

이렇게 했다. 해당 메서드는

public void addComment(Comment comment) {
        this.comments.add(comment);
}

지금 한 건 메모리 commentList에 저장한거라 껏다 키면 사라짐

근데 지금 h2를 사용해서 개발을 진행하다 보니 내가 인지를 못한거지

다른 db를 사용했으면 서버를 껐다가 키면 addComment는 사라지고 db엔 없는 고런 느낌

그래서 레파지토리에서 코멘트 내역을 불러와서 리스트에 저장해야 db에 저장되는거임

그래서 저 add부분을 지웠다.

그리고 @OneToMany를 안쓰기위해

// CommentService.java
@Transactional
public List<CommentResponseDto> getCommentsByPostId(Long postId) {
    // OneToMany를 안쓸 수 있는 방법이 뭐야
    List<Comment> comments = commentRepository.findAllByPostId(postId);
    List<CommentResponseDto> list = new ArrayList<>();
    for (Comment dbComment : comments) {
        list.add(new CommentResponseDto(dbComment));
    }
    return list;
}

// PostService.java
private final CommentService commentService;
...

@Transactional(readOnly = true)
public List<PostResponseDto> getAllBlogs() {

    List<Post> posts = postRepository.findAllByOrderByModifiedAtDesc();
    List<PostResponseDto> postResponseDto = new ArrayList<>();
    for (Post post : posts){
        List<CommentResponseDto> list = commentService.getCommentsByPostId(post.getId());
        postResponseDto.add(new PostResponseDto(post, list));
    }

    return postResponseDto;
}

@Transactional(readOnly = true)
public PostResponseDto getPosts(Long id) {
    Post post = postRepository.findById(id).orElseThrow(
            () -> new IllegalArgumentException("해당 게시글이 존재하지 않습니다.")
    );
    List<CommentResponseDto> list = commentService.getCommentsByPostId(id);
    return new PostResponseDto(post, list);
}

이렇게 해봄

게시글 좋아요에 스프링시큐리티를 적용시키면서 에러

게시글의 작성자가 아닌 사용자가 좋아요를 할 때 접근권한이 없다는 오류가 나온다.

@PostMapping("/posts/{id}")
    public ResponseEntity<String> likeOrDislikePost(@PathVariable Long id, @AuthenticationPrincipal UserDetailsImpl userDetails) {
        String username = userDetails.getUsername();
        return postService.likeOrDislikePost(id, username);
    }

원래 return postService.likeOrDislikePost(id, userDetails.getUser()); 으로 되어있고
서비스단에서

public ResponseEntity<String> likeOrDislikePost(Long id, User user) {
        Post post = postRepository.findByIdAndUserId(id, user.getId()).orElseThrow(
                () -> new IllegalArgumentException("해당 게시글이 존재하지 않습니다.")
		);
        ...
        PostLike postLike = postLikeRepository.save(new PostLike(user.getUsername(), post));
        ...
}

userId를 사용해서 레파지토리에서 포스트를 불러와서 그걸 저장을 하게 되니까 좋아요를 요청한 사람이 쓰지 않은 글은 불러오지 않은거임 그래서 오류가..

 Post post = postRepository.findById(id).orElseThrow(
                () -> new IllegalArgumentException("해당 게시글이 존재하지 않습니다.")
);

이렇게 해서 postId만 사용해서 게시글을 불러왔다.

튜터님 코드리뷰

현재 좋아요와 좋아요취소 기능이 하나의 api로 되어있는데
좋아요 api → 젛아요 누른 정보 조회 api → dislike api
api 분리를 하는게 좋음
하나로만 되어있으면 클라이언트에서 좋아요를 했는지 안했는지 모름 그럼 바디로 해당 상태를 넘겨줘야하고 그렇게 되면 바디가 약간만 달라져도 안됨 수정 안됨

프론트엔드 관점에서 api를 호출해보는게 좋음 js로 호출만..

항상 상대방 입장에서 생각해서 로직을 작성해야함.
여러개 기능이 하나에 묶여있는거 않좋음

profile
기록하자기록해!

0개의 댓글