오늘 공부한 것
* 마이페이지의 댓글 대댓글 조회 기능 수정
* WebSocket 사용한 채팅 기능 구현
오늘은 마이페이지에 들어가는 댓글과 대댓글 조회기능을 수정했다
원래는 게시글 별로 내가 쓴 댓글과 대댓글을 조회하도록 만들었다면
프론트엔드의 요청으로 내가 쓴 댓글과 대댓글을 모두 조회할 수 있도록 변경하였다.
1. 댓글
1) Controller
Api와 postId 삭제
// 마이페이지에서 내가 쓴 댓글 조회
@Operation(summary = "사용자별 댓글 조회", description = "사용자가 쓴 댓글 조회 api 입니다.")
@GetMapping("/commentsme")
public ResponseEntity<Slice<CommentsMeResponseDto>> commentsMeList(@AuthenticationPrincipal UserDetailsImpl userDetails,
@PageableDefault Pageable pageable) {
return ResponseEntity.ok(commentsService.commentsMeList(userDetails.getUsers(), pageable));
}
2) Dto
Nickname 삭제 및 createAt 추가
@Getter
public class CommentsMeResponseDto {
private Long commnetId;
private String contents;
private String title;
private LocalDateTime createAt;
public CommentsMeResponseDto(Comments comments, String postTitle) {
this.commnetId = comments.getId();
this.contents = comments.getContents();
this.title = postTitle;
this.createAt = comments.getCreatedAt();
}
}
3) Service
postId 삭제
findByPosts_IdAndEmailOrderByCreatedAtDesc -> findAllByAndEmailOrderByCreatedAtDesc 로 변경
Nickname 삭제
// 마이페이지에서 내가 쓴 댓글 조회
public Slice<CommentsMeResponseDto> commentsMeList (Users users,
Pageable pageable) {
Slice<Comments> commentsMeList = commentsRepository.findAllByAndEmailOrderByCreatedAtDesc(users.getEmail(), pageable);
if (commentsMeList.isEmpty()) {
throw new CustomException(ErrorCode.POST_NOT_EXIST); // 존재하지 않는 게시글입니다
}
List<CommentsMeResponseDto> CommentsMeResponseDtoList = new ArrayList<>();
for (Comments comments : commentsMeList) {
CommentsMeResponseDtoList.add(new CommentsMeResponseDto(comments, comments.getPosts().getTitle()));
}
return new SliceImpl<>(CommentsMeResponseDtoList, pageable, commentsMeList.hasNext());
}
4) Repository
public interface CommentsRepository extends JpaRepository<Comments, Long> {
List<Comments> findByPosts(Posts posts);
int countByPosts(Posts posts);
Slice<Comments> findByPosts_IdOrderByCreatedAtDesc(Long postId, Pageable pageable);
Slice<Comments> findAllByAndEmailOrderByCreatedAtDesc(String email, Pageable pageable);
}
2. 대댓글
1) Controller
Api와 commentId 삭제
// 마이페이지에서 내가 쓴 대댓글 조회
@Operation(summary = "사용자별 대댓글 조회", description = "사용자가 쓴 대댓글 조회 api 입니다.")
@GetMapping("/repliesme")
public ResponseEntity<Slice<RepliesMeResponseDto>> repliesMeList(@AuthenticationPrincipal UserDetailsImpl userDetails,
@PageableDefault Pageable pageable) {
return ResponseEntity.ok(repliesService.repliesMeList(userDetails.getUsers(), pageable));
}
2) Dto
Nickname 삭제 및 createAt 추가
@Getter
public class RepliesMeResponseDto {
private Long repliesId;
private String contents;
private String title;
private LocalDateTime createAt;
public RepliesMeResponseDto(Replies replies, String postTitle) {
this.repliesId = replies.getId();
this.contents = replies.getContents();
this.title = postTitle;
this.createAt = replies.getCreatedAt();
}
}
3) Service
commentId삭제
findByComments_IdAndEmailOrderByCreatedAtDesc-> findAllByAndEmailOrderByCreatedAtDesc 로 변경
Nickname 삭제
// 마이페이지에서 내가 쓴 대댓글 조회
public Slice<RepliesMeResponseDto> repliesMeList(Users users,
Pageable pageable) {
Slice<Replies> repliesMeList = repliesRepository.findAllByAndEmailOrderByCreatedAtDesc(users.getEmail(), pageable);
if (repliesMeList.isEmpty()) {
throw new CustomException(ErrorCode.COMMENTS_NOT_EXIST); // 존재하지 않는 댓글입니다
}
List<RepliesMeResponseDto> RepliesMeResponseDtoList = new ArrayList<>();
for (Replies replies : repliesMeList) {
RepliesMeResponseDtoList.add(new RepliesMeResponseDto(replies, replies.getComments().getPosts().getTitle()));
}
return new SliceImpl<>(RepliesMeResponseDtoList, pageable, repliesMeList.hasNext());
}
4) Repository
public interface RepliesRepository extends JpaRepository<Replies, Long> {
Slice<Replies> findByComments_IdOrderByCreatedAtDesc(Long commentId, Pageable pageable);
Slice<Replies> findAllByAndEmailOrderByCreatedAtDesc(String email, Pageable pageable);
}
또한, 계속해서 WebSocket 사용한 채팅 기능 구현을 했다
현제 구현중이던 곳에 적용하려고 하니 아무래도 JWT 부분과 충돌이 일어나는지 제대로 실행이 되지않았다
그래서 아에 새로운 프로젝트를 생성해서 연습삼아서 거기에 먼저해보고 우리프로젝트에 적용해보기로했다.
1. Config
@EnableWebSocket : WebSocket을 활성화
/ws/chat : WebSocket 에 접속하기 위한 endpoint
setAllowedOrigins("*") : Cors 방지
@RequiredArgsConstructor
@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {
private final WebSocketHandler webSocketHandler;
@Override
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
registry.addHandler(webSocketHandler, "/ws/chat").setAllowedOrigins("*");
}
}
2. Handler
payload : 전송되는 데이터
@Slf4j
@Component
public class WebSocketChatHandler extends TextWebSocketHandler {
@Override
protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
String payload = message.getPayload();
log.info("payload {}", payload);
TextMessage textMessage = new TextMessage("Welcome chatting sever~^^");
session.sendMessage(textMessage);
}
}
3. 실행
'항해99' 카테고리의 다른 글
23.10.19 항해 99 16기 실전 프로젝트 14일차 (1) | 2023.10.19 |
---|---|
23.10.18 항해 99 16기 실전 프로젝트 13일차 (1) | 2023.10.18 |
23.10.16 항해 99 16기 실전 프로젝트 11일차 (0) | 2023.10.16 |
23.10.09~10.15 항해 99 16기 8주차 회고록 (1) | 2023.10.15 |
23.10.14 항해 99 16기 실전 프로젝트 10일차 (1) | 2023.10.14 |