Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[refactor] 게시물 조회 관련 api 보완 (응답값 추가) #24

Merged
merged 6 commits into from
Jun 10, 2024
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
import com.SafeNet.Backend.domain.member.entity.Member;
import com.SafeNet.Backend.domain.member.repository.MemberRepository;
import com.SafeNet.Backend.domain.message.entity.Message;
import com.SafeNet.Backend.domain.message.dto.MessageRequestDto;
import com.SafeNet.Backend.domain.message.dto.MessageResponseDto;
import com.SafeNet.Backend.domain.message.repository.MessageRepository;
import com.SafeNet.Backend.domain.messageroom.entity.MessageRoom;
Expand Down Expand Up @@ -49,7 +48,7 @@ public MessageRoomService(
MemberRepository memberRepository,
RedisMessageListenerContainer redisMessageListener,
RedisSubscriber redisSubscriber,
@Qualifier("redisTemplate") RedisTemplate<String, Object> redisTemplate) {
@Qualifier("customRedisTemplate") RedisTemplate<String, Object> redisTemplate) {
this.messageRoomRepository = messageRoomRepository;
this.messageRepository = messageRepository;
this.postRepository = postRepository;
Expand All @@ -68,7 +67,11 @@ private void init() {
// 1:1 채팅방 생성
public MessageResponseDto createRoom(Long postId, String email) {
Member member = memberRepository.findByEmail(email).orElseThrow(() -> new PostException("Member not found with email: " + email, HttpStatus.NOT_FOUND));
Post post = postRepository.findById(postId).orElseThrow(() -> new IllegalArgumentException("게시글을 찾을 수 없습니다."));
Post post = postRepository.findById(postId).orElseThrow(() -> new PostException("Post not found with id: " + postId, HttpStatus.NOT_FOUND));

if (post.getMember().getEmail().equals(email)) {
throw new PostException("You cannot create a chat room for your own post", HttpStatus.BAD_REQUEST); // 게시물 작성자인 경우 채팅방을 생성하지 못하도록 예외 처리
}

String receiver = post.getMember().getName(); // 게시물의 작성자를 receiver로 설정

Expand Down Expand Up @@ -174,17 +177,17 @@ public MessageRoomDto findRoom(String roomId, String email) {
Member member = memberRepository.findByEmail(email).orElseThrow(() -> new PostException("Member not found with email: " + email, HttpStatus.NOT_FOUND));

MessageRoom messageRoom = messageRoomRepository.findByRoomId(roomId)
.orElseThrow(() -> new IllegalArgumentException("해당 쪽지방이 존재하지 않습니다."));
.orElseThrow(() -> new IllegalArgumentException("The chat room does not exist."));

// 게시글 검증 없이 메시지룸의 post 참조
Post post = messageRoom.getPost();
if (post == null) {
throw new IllegalArgumentException("쪽지방에 연결된 게시물이 존재하지 않습니다.");
throw new IllegalArgumentException("The chat room is not connected to any post.");
}

// sender 또는 receiver 확인
if (!messageRoom.getSender().equals(member.getName()) && !messageRoom.getReceiver().equals(member.getName())) {
throw new IllegalArgumentException("해당 쪽지방에 접근할 권한이 없습니다.");
throw new IllegalArgumentException("You do not have permission to access this chat room.");
}

return MessageRoomDto.builder()
Expand Down Expand Up @@ -227,7 +230,7 @@ else if (member.getName().equals(messageRoom.getReceiver())) {
messageRoomRepository.delete(messageRoom);
opsHashMessageRoom.delete(Message_Rooms, messageRoom.getRoomId());
return MessageResponseDto.builder()
.message("receiver와 sender가 모두 방을 나갔습니다.")
.message("Both the receiver and the sender have left the room.")
.status(HttpStatus.OK.value())
.build();
} else {
Expand All @@ -247,7 +250,7 @@ else if (member.getName().equals(messageRoom.getReceiver())) {
opsHashMessageRoom.put(Message_Rooms, messageRoomDto.getRoomId(), messageRoomDto); // Redis 업데이트

return MessageResponseDto.builder()
.message("상대방이 방을 나갔으므로 더 이상 채팅이 불가능합니다.")
.message("The other person has left the room, so further chatting is not possible.")
.status(HttpStatus.OK.value())
.build();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,8 @@ public ResponseEntity<?> getPostById(
@RequestHeader(name = "ACCESS_TOKEN", required = false) String accessToken,
@RequestHeader(name = "REFRESH_TOKEN", required = false) String refreshToken,
@PathVariable("postId") Long postId) {
Optional<PostResponseDto> postById = postService.getPostById(postId);
String email = getUserEmail();
Optional<PostResponseDto> postById = postService.getPostById(postId, email);
if (postById.isPresent()) {
return ResponseEntity.ok(postById.get());
} else {
Expand Down Expand Up @@ -103,7 +104,7 @@ public ResponseEntity<String> deletePost(
}

@PatchMapping("/{postId}/status/trading")
@Operation(summary = "게시물 상태 거래중으로 변경", description = "채팅방에서 '거래중'으로 변경할 때 사용하는 API")
@Operation(summary = "게시물 상태 거래중으로 변경", description = "판매자가 채팅방에서 '거래중'으로 변경할 때 사용하는 API")
public ResponseEntity<String> updatePostStatusToTrading(
@RequestHeader(name = "ACCESS_TOKEN", required = false) String accessToken,
@RequestHeader(name = "REFRESH_TOKEN", required = false) String refreshToken,
Expand All @@ -114,7 +115,7 @@ public ResponseEntity<String> updatePostStatusToTrading(
}

@PatchMapping("/{postId}/status/completed")
@Operation(summary = "게시물 상태 거래완료로 변경", description = "채팅방에서 '거래완료'로 변경할 때 사용하는 API")
@Operation(summary = "게시물 상태 거래완료로 변경", description = "판매자가 채팅방에서 '거래완료'로 변경할 때 사용하는 API")
public ResponseEntity<String> updatePostStatusToCompleted(
@RequestHeader(name = "ACCESS_TOKEN", required = false) String accessToken,
@RequestHeader(name = "REFRESH_TOKEN", required = false) String refreshToken,
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package com.SafeNet.Backend.domain.post.dto;

import com.SafeNet.Backend.domain.post.entity.Category;
import com.SafeNet.Backend.domain.post.entity.PostStatus;
import com.fasterxml.jackson.annotation.JsonInclude;
import lombok.Builder;
import lombok.Getter;
Expand All @@ -20,4 +21,6 @@ public class PostResponseDto {
private String contents;
private String writer;
private int cost;
private boolean isMine; // 현재 사용자가 등록한 글인지
private PostStatus postStatus; // 현재 게시글의 상태
}
Original file line number Diff line number Diff line change
Expand Up @@ -34,29 +34,34 @@ private Long getMemberRegionId(String email) {
return region.getId();
}

public List<PostResponseDto> convertPostsToDto(List<Post> posts, Long memberId) {
public List<PostResponseDto> convertPostsToDto(List<Post> posts, Long memberId, String email) {
return posts.stream().map(post -> {
boolean isLikedByCurrentUser = postLikeRepository.existsByPostIdAndMemberId(post.getId(), memberId);
return PostDtoConverter.convertToDto(post, isLikedByCurrentUser);
boolean isLikedByCurrentUser = post.getPostLikeList().stream()
.anyMatch(like -> like.getMember().getId().equals(memberId));
return PostDtoConverter.convertToDto(post, isLikedByCurrentUser, post.getMember().getEmail().equals(email), post.getPostStatus());
}).collect(Collectors.toList());
}

// 게시물 리스트 조회
public List<PostResponseDto> getAllPosts(String email) {
Member member = getMemberByEmail(email);
Long memberId = member.getId(); // MemberId 추출
Region region = member.getRegion();
Region region = member.getRegion(); // 지역 추출
Long memberRegionId = region.getId(); // 멤버의 RegionId 추출
List<Post> posts = postRepository.findByRegion_Id(memberRegionId);
return convertPostsToDto(posts, memberId);
return convertPostsToDto(posts, memberId, email);
}

public void getPostById(String email) {
getMemberByEmail(email);
}

// 사용자가 등록한 게시물 조회
// 사용자가 등록한 게시물 조회
public List<PostResponseDto> getPostsByMemberId(String email) {
Member member = getMemberByEmail(email);
Long memberId = member.getId();
List<Post> posts = postRepository.findByMember_Id(memberId);
return convertPostsToDto(posts, memberId);
return convertPostsToDto(posts, memberId, email);
}

// 사용자가 좋아요 누른 게시물 조회
Expand All @@ -66,7 +71,7 @@ public List<PostResponseDto> getLikedPostsByMemberId(String email) {
List<Post> posts = postLikeRepository.findByMember_Id(memberId).stream()
.map(PostLike::getPost)
.collect(Collectors.toList());
return convertPostsToDto(posts, memberId);
return convertPostsToDto(posts, memberId, email);
}

// 키워드로 게시물 조회
Expand Down Expand Up @@ -105,7 +110,7 @@ public List<PostResponseDto> sortPostsByBuyDate(String email) {
private List<PostResponseDto> getPostResponseDtos(String email, List<Post> posts) {
Member member = getMemberByEmail(email);
Long memberId = member.getId();
return convertPostsToDto(posts, memberId);
return convertPostsToDto(posts, memberId, email);
}
}

Original file line number Diff line number Diff line change
@@ -1,7 +1,12 @@
package com.SafeNet.Backend.domain.post.service;

import com.SafeNet.Backend.domain.member.entity.Member;
import com.SafeNet.Backend.domain.member.repository.MemberRepository;
import com.SafeNet.Backend.domain.member.service.MemberService;
import com.SafeNet.Backend.domain.post.dto.PostResponseDto;
import com.SafeNet.Backend.domain.post.exception.PostException;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

Expand All @@ -12,12 +17,15 @@
@RequiredArgsConstructor
public class MemberItemService {
private final CommonPostService commonPostService;
private final MemberRepository memberRepository;

public List<PostResponseDto> getPostsByMemberId(String email) {
Member member = memberRepository.findByEmail(email).orElseThrow(() -> new PostException("Member not found with email: " + email, HttpStatus.NOT_FOUND)); // 유효한 멤버인지 검사
return commonPostService.getPostsByMemberId(email);
}

public List<PostResponseDto> getLikedPostsByMemberId(String email) {
Member member = memberRepository.findByEmail(email).orElseThrow(() -> new PostException("Member not found with email: " + email, HttpStatus.NOT_FOUND)); // 유효한 멤버인지 검사
return commonPostService.getLikedPostsByMemberId(email);
}
}
Original file line number Diff line number Diff line change
@@ -1,8 +1,12 @@
package com.SafeNet.Backend.domain.post.service;

import com.SafeNet.Backend.domain.member.entity.Member;
import com.SafeNet.Backend.domain.member.repository.MemberRepository;
import com.SafeNet.Backend.domain.post.dto.PostResponseDto;
import com.SafeNet.Backend.domain.post.entity.Category;
import com.SafeNet.Backend.domain.post.exception.PostException;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

Expand All @@ -13,20 +17,24 @@
@RequiredArgsConstructor
public class PostSearchAndSortService {
private final CommonPostService commonPostService;

private final MemberRepository memberRepository;
public List<PostResponseDto> searchByKeyWord(String keyword, String email) {
Member member = memberRepository.findByEmail(email).orElseThrow(() -> new PostException("Member not found with email: " + email, HttpStatus.NOT_FOUND)); // 유효한 멤버인지 검사
return commonPostService.searchPostsByKeyword(keyword, email);
}

public List<PostResponseDto> searchByCategory(Category category, String email) {
Member member = memberRepository.findByEmail(email).orElseThrow(() -> new PostException("Member not found with email: " + email, HttpStatus.NOT_FOUND)); // 유효한 멤버인지 검사
return commonPostService.searchPostsByCategory(category, email);
}

public List<PostResponseDto> sortByCreated(String email) {
Member member = memberRepository.findByEmail(email).orElseThrow(() -> new PostException("Member not found with email: " + email, HttpStatus.NOT_FOUND)); // 유효한 멤버인지 검사
return commonPostService.sortPostsByCreated(email);
}

public List<PostResponseDto> sortByBuyDate(String email) {
Member member = memberRepository.findByEmail(email).orElseThrow(() -> new PostException("Member not found with email: " + email, HttpStatus.NOT_FOUND)); // 유효한 멤버인지 검사
return commonPostService.sortPostsByBuyDate(email);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,13 @@
import com.SafeNet.Backend.domain.file.service.FileStorageService;
import com.SafeNet.Backend.domain.file.service.S3Service;
import com.SafeNet.Backend.domain.member.entity.Member;
import com.SafeNet.Backend.domain.member.repository.MemberRepository;
import com.SafeNet.Backend.domain.post.dto.PostRequestDto;
import com.SafeNet.Backend.domain.post.dto.PostResponseDto;
import com.SafeNet.Backend.domain.post.entity.Post;
import com.SafeNet.Backend.domain.post.entity.PostStatus;
import com.SafeNet.Backend.domain.post.exception.PostException;
import com.SafeNet.Backend.domain.post.repository.PostRepository;
import com.SafeNet.Backend.domain.post.util.PostDtoConverter;
import com.SafeNet.Backend.domain.region.entity.Region;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
Expand All @@ -25,6 +25,7 @@
import java.util.List;
import java.util.Optional;


@Service
@Transactional(readOnly = true)
@RequiredArgsConstructor
Expand Down Expand Up @@ -67,11 +68,12 @@ public List<PostResponseDto> getAllPosts(String email) {
}

// 게시물 상세 조회
public Optional<PostResponseDto> getPostById(Long id) {
return postRepository.findById(id).map(PostService::convertToDetailDto);
public Optional<PostResponseDto> getPostById(Long id, String email) {
commonPostService.getPostById(email); // 게시물 상세보기를 하기 전 유효한 사용자인지 체크
return postRepository.findById(id).map(post -> convertToDetailDto(post, post.getMember().getEmail().equals(email), post.getPostStatus()));
}

private static PostResponseDto convertToDetailDto(Post post) {
private static PostResponseDto convertToDetailDto(Post post, boolean isMine, PostStatus postStatus) {
return PostResponseDto.builder()
.postId(post.getId())
.category(post.getCategory())
Expand All @@ -83,14 +85,16 @@ private static PostResponseDto convertToDetailDto(Post post) {
.contents(post.getContents())
.writer(post.getMember().getName())
.cost(post.getCost())
.isMine(isMine)
.postStatus(postStatus)
.build();
}


@Transactional
public void updatePost(Long id, PostRequestDto postRequestDto, MultipartFile receiptImage, MultipartFile productImage, String email) {
Post existingPost = postRepository.findById(id).orElseThrow(() -> new PostException("Post not found with id: " + id, HttpStatus.NOT_FOUND));
if (!existingPost.getMember().getEmail().equals(email)) {
if (!existingPost.getMember().getEmail().equals(email)) { // 존재하는 사용자인지 & 글 등록한 사람인지 검사
throw new PostException("You do not have permission to update this post", HttpStatus.FORBIDDEN); // 글을 등록한 사람만 수정할 수 있는 권한이 있다.
}
try {
Expand Down Expand Up @@ -123,8 +127,8 @@ public void updatePost(Long id, PostRequestDto postRequestDto, MultipartFile rec
@Transactional
public void deletePost(Long id, String email) {
Post post = postRepository.findById(id).orElseThrow(() -> new PostException("Post not found with id: " + id, HttpStatus.NOT_FOUND));
if (!post.getMember().getEmail().equals(email)) { // 글을 등록한 사람만 삭제할 권한이 있다.
throw new PostException("You do not have permission to delete this post", HttpStatus.FORBIDDEN);
if (!post.getMember().getEmail().equals(email)) { // 존재하는 사용자인지 & 글 등록한 사람인지 검사
throw new PostException("You do not have permission to delete this post", HttpStatus.FORBIDDEN); // 글을 등록한 사람만 삭제할 권한이 있다.
}
try {
if (post.getPostStatus() != PostStatus.거래가능) {
Expand All @@ -139,9 +143,9 @@ public void deletePost(Long id, String email) {

@Transactional
public void updatePostStatusToTrading(Long id, String email) {
Post post = postRepository.findById(id).orElseThrow(() -> new PostException("Post not found with id: " + id, HttpStatus.NOT_FOUND));
if (!post.getMember().getEmail().equals(email)) { // 글을 등록한 사람만상태를 바꿀 수 있는 권한이 있다.
throw new PostException("You do not have permission to change this post status to trading", HttpStatus.FORBIDDEN);
Post post = postRepository.findById(id).orElseThrow(() -> new PostException("Post not found", HttpStatus.NOT_FOUND));
if (!post.getMember().getEmail().equals(email)) { // 존재하는 사용자인지 &등록한 사람인지 검사
throw new PostException("You do not have permission to change this post status to trading", HttpStatus.FORBIDDEN); // 글을 등록한 사람만 글 상태를 바꿀 수 있는 권한이 있다.
}
try {
post.setPostStatus(PostStatus.거래중);
Expand All @@ -153,9 +157,10 @@ public void updatePostStatusToTrading(Long id, String email) {

@Transactional
public void updatePostStatusToCompleted(Long id, String email) {
Post post = postRepository.findById(id).orElseThrow(() -> new PostException("Post not found with id: " + id, HttpStatus.NOT_FOUND));
if (!post.getMember().getEmail().equals(email)) { // 글을 등록한 사람만 글 상태를 바꿀 수 있는 권한이 있다.
throw new PostException("You do not have permission to change this post status to completed", HttpStatus.FORBIDDEN);
Post post = postRepository.findById(id).orElseThrow(() -> new PostException("Post not found", HttpStatus.NOT_FOUND));
if (!post.getMember().getEmail().equals(email)) { // 존재하는 사용자인지 & 글 등록한 사람인지 검사
throw new PostException("You do not have permission to change this post status to completed", HttpStatus.FORBIDDEN); // 글을 등록한 사람만 글 상태를 바꿀 수 있는 권한이 있다.

}
try {
post.setPostStatus(PostStatus.거래완료);
Expand All @@ -164,4 +169,4 @@ public void updatePostStatusToCompleted(Long id, String email) {
throw new PostException("Failed to update post status to trading", HttpStatus.INTERNAL_SERVER_ERROR);
}
}
}
}
Loading
Loading