Skip to content

Commit

Permalink
Merge pull request #15 from SafeNet-2024/feature/post&message-api-test
Browse files Browse the repository at this point in the history
Feature/post&message api test
  • Loading branch information
Yeon-chae authored Jun 3, 2024
2 parents adf42a9 + d4bb735 commit 709629c
Show file tree
Hide file tree
Showing 13 changed files with 227 additions and 224 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -20,10 +20,10 @@ public class MemberItemController {
private final MemberItemService memberItemService;

@GetMapping("/my-posts")
public ResponseEntity<?> getPostsByMemberId(@RequestHeader(name = "ACCESS_TOKEN", required = false) String accessToken,
@RequestHeader(name = "REFRESH_TOKEN", required = false) String refreshToken) {
public ResponseEntity<?> getPostsByMemberId(
@RequestHeader(name = "ACCESS_TOKEN", required = false) String accessToken,
@RequestHeader(name = "REFRESH_TOKEN", required = false) String refreshToken) {
String email = getUserEmail();

List<PostResponseDto> posts = memberItemService.getPostsByMemberId(email);
if (posts.isEmpty()) {
return ResponseEntity.ok("사용자가 등록한 게시물이 없습니다.");
Expand All @@ -32,16 +32,17 @@ public ResponseEntity<?> getPostsByMemberId(@RequestHeader(name = "ACCESS_TOKEN"
}

@GetMapping("/liked-posts")
public ResponseEntity<?> getLikedPostsByMemberId(@RequestHeader(name = "ACCESS_TOKEN", required = false) String accessToken,
@RequestHeader(name = "REFRESH_TOKEN", required = false) String refreshToken) {
public ResponseEntity<?> getLikedPostsByMemberId(
@RequestHeader(name = "ACCESS_TOKEN", required = false) String accessToken,
@RequestHeader(name = "REFRESH_TOKEN", required = false) String refreshToken) {
String email = getUserEmail();

List<PostResponseDto> likedPosts = memberItemService.getLikedPostsByMemberId(email);
if (likedPosts.isEmpty()) {
return ResponseEntity.ok("등록된 찜이 없습니다.");
}
return ResponseEntity.ok(likedPosts);
}

@ExceptionHandler(PostException.class)
public ResponseEntity<String> handleCustomException(PostException e) {
return ResponseEntity.status(e.getStatus()).body(e.getMessage());
Expand All @@ -52,4 +53,4 @@ private static String getUserEmail() {
UserDetailsImpl userDetails = (UserDetailsImpl) principal;
return userDetails.getUsername();
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@
import com.SafeNet.Backend.domain.post.dto.PostRequestDto;
import com.SafeNet.Backend.domain.post.dto.PostResponseDto;
import com.SafeNet.Backend.domain.post.exception.PostException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.SafeNet.Backend.domain.post.service.PostService;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.core.JsonProcessingException;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
Expand Down Expand Up @@ -43,18 +43,19 @@ public ResponseEntity<String> createPost(
@RequestPart(value = "receiptImage") MultipartFile receiptImage,
@RequestPart(value = "productImage") MultipartFile productImage) throws JsonProcessingException {
PostRequestDto postRequestDto = objectMapper.readValue(postRequestDtoJson, PostRequestDto.class); // JSON 객체를 PostRequestDto로 변환

String email = getUserEmail();

postService.createPost(postRequestDto, receiptImage, productImage, email);
return ResponseEntity.status(HttpStatus.CREATED).body("Post created successfully");
}


@GetMapping
@Operation(summary = "전체 게시물 불러오기", description = "전체 게시물 리스트 볼 때 사용하는 API")
public ResponseEntity<?> getAllPosts() {
List<PostResponseDto> allPosts = postService.getAllPosts();
@Operation(summary = "게시물 리스트 불러오기", description = "전체 게시물을 리스트로 볼 때 사용하는 API")
public ResponseEntity<?> getPosts(
@RequestHeader(name = "ACCESS_TOKEN", required = false) String accessToken,
@RequestHeader(name = "REFRESH_TOKEN", required = false) String refreshToken
) {
String email = getUserEmail();
List<PostResponseDto> allPosts = postService.getAllPosts(email);
if (allPosts.isEmpty()) {
return ResponseEntity.ok("등록된 게시물이 없습니다.");
}
Expand All @@ -63,7 +64,10 @@ public ResponseEntity<?> getAllPosts() {

@GetMapping("/{postId}")
@Operation(summary = "특정 게시물 불러오기", description = "특정 게시물 상세보기 할 때 사용하는 API")
public ResponseEntity<?> getPostById(@PathVariable("postId") Long id) {
public ResponseEntity<?> getPostById(
@RequestHeader(name = "ACCESS_TOKEN", required = false) String accessToken,
@RequestHeader(name = "REFRESH_TOKEN", required = false) String refreshToken,
@PathVariable("postId") Long id) {
Optional<PostResponseDto> postById = postService.getPostById(id);
if (postById.isPresent()) {
return ResponseEntity.ok(postById.get());
Expand All @@ -83,7 +87,6 @@ public ResponseEntity<String> updatePost(
@RequestPart(value = "productImage", required = false) MultipartFile productImage) throws JsonProcessingException {
PostRequestDto postRequestDto = new ObjectMapper().readValue(postRequestDtoJson, PostRequestDto.class);
String email = getUserEmail();

postService.updatePost(id, postRequestDto, receiptImage, productImage, email);
return ResponseEntity.ok("Post updated successfully");
}
Expand Down Expand Up @@ -129,4 +132,4 @@ private static String getUserEmail() {
UserDetailsImpl userDetails = (UserDetailsImpl) principal;
return userDetails.getUsername();
}
}
}
Original file line number Diff line number Diff line change
@@ -1,12 +1,14 @@
package com.SafeNet.Backend.domain.post.controller;

import com.SafeNet.Backend.domain.member.entity.UserDetailsImpl;
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 com.SafeNet.Backend.domain.post.service.PostSearchAndSortService;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import java.util.List;
Expand All @@ -19,31 +21,53 @@ public class PostSearchAndSortController {
private final PostSearchAndSortService postSearchAndSortService;

@GetMapping("/keyword")
public ResponseEntity<List<PostResponseDto>> searchByKeyWord(@RequestParam("keyword") String keyword) {
List<PostResponseDto> posts = postSearchAndSortService.searchByKeyWord(keyword);
public ResponseEntity<List<PostResponseDto>> searchByKeyWord(
@RequestHeader(name = "ACCESS_TOKEN", required = false) String accessToken,
@RequestHeader(name = "REFRESH_TOKEN", required = false) String refreshToken,
@RequestParam("keyword") String keyword) {
String email = getUserEmail();
List<PostResponseDto> posts = postSearchAndSortService.searchByKeyWord(keyword, email);
return ResponseEntity.ok(posts);
}

@GetMapping("/category")
public ResponseEntity<List<PostResponseDto>> searchByCategory(@RequestParam("category") Category category) {
List<PostResponseDto> posts = postSearchAndSortService.searchByCategory(category);
public ResponseEntity<List<PostResponseDto>> searchByCategory(
@RequestHeader(name = "ACCESS_TOKEN", required = false) String accessToken,
@RequestHeader(name = "REFRESH_TOKEN", required = false) String refreshToken,
@RequestParam("category") Category category) {
String email = getUserEmail();
List<PostResponseDto> posts = postSearchAndSortService.searchByCategory(category, email);
return ResponseEntity.ok(posts);
}

@GetMapping("/sort/created")
public ResponseEntity<List<PostResponseDto>> sortByCreated() {
List<PostResponseDto> posts = postSearchAndSortService.sortByCreated();
public ResponseEntity<List<PostResponseDto>> sortByCreated(
@RequestHeader(name = "ACCESS_TOKEN", required = false) String accessToken,
@RequestHeader(name = "REFRESH_TOKEN", required = false) String refreshToken
) {
String email = getUserEmail();
List<PostResponseDto> posts = postSearchAndSortService.sortByCreated(email);
return ResponseEntity.ok(posts);
}

@GetMapping("/sort/buyDate")
public ResponseEntity<List<PostResponseDto>> sortByBuyDate() {
List<PostResponseDto> posts = postSearchAndSortService.sortByBuyDate();
public ResponseEntity<List<PostResponseDto>> sortByBuyDate(
@RequestHeader(name = "ACCESS_TOKEN", required = false) String accessToken,
@RequestHeader(name = "REFRESH_TOKEN", required = false) String refreshToken
) {
String email = getUserEmail();
List<PostResponseDto> posts = postSearchAndSortService.sortByBuyDate(email);
return ResponseEntity.ok(posts);
}

@ExceptionHandler(PostException.class)
public ResponseEntity<String> handleCustomException(PostException e) {
return ResponseEntity.status(e.getStatus()).body(e.getMessage());
}
}

private static String getUserEmail() {
Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
UserDetailsImpl userDetails = (UserDetailsImpl) principal;
return userDetails.getUsername();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
public class PostResponseDto {
private Long postId;
private Category category;
private int likeCount;
private boolean likeCount; // 현재 사용자가 하트를 눌렀는지 여부
private String productImageUrl; // 상품 이미지 URL
private String receiptImageUrl; // 영수증 이미지 URL
private String title;
Expand All @@ -21,4 +21,3 @@ public class PostResponseDto {
private String writer;
private int cost;
}

Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
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.entity.Post;
import com.SafeNet.Backend.domain.post.exception.PostException;
import com.SafeNet.Backend.domain.post.repository.PostRepository;
import com.SafeNet.Backend.domain.postLike.repository.PostLikeRepository;
import com.SafeNet.Backend.domain.post.util.PostDtoConverter;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class CommonPostService {
private final PostRepository postRepository;
private final MemberRepository memberRepository;
private final PostLikeRepository postLikeRepository;

public Member getMemberByEmail(String email) {
return memberRepository.findByEmail(email).orElseThrow(() -> new PostException("Member not found with email: " + email, HttpStatus.NOT_FOUND));
}

public List<PostResponseDto> convertPostsToDto(List<Post> posts, Long memberId) {
return posts.stream().map(post -> {
boolean isLikedByCurrentUser = postLikeRepository.existsByPostIdAndMemberId(post.getId(), memberId);
return PostDtoConverter.convertToDto(post, isLikedByCurrentUser);
}).collect(Collectors.toList());
}

public List<PostResponseDto> getAllPosts(String email) {
Member member = getMemberByEmail(email);
Long memberId = member.getId();
List<Post> posts = postRepository.findAll();
return convertPostsToDto(posts, memberId);
}

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);
}

public List<PostResponseDto> getLikedPostsByMemberId(String email) {
Member member = getMemberByEmail(email);
Long memberId = member.getId();
List<Post> posts = postLikeRepository.findByMember_Id(memberId).stream()
.map(postLike -> postLike.getPost())
.collect(Collectors.toList());
return convertPostsToDto(posts, memberId);
}

public List<PostResponseDto> searchPostsByKeyword(String keyword, String email) {
Member member = getMemberByEmail(email);
Long memberId = member.getId();
List<Post> posts = postRepository.findByTitleContainingOrContentsContaining(keyword, keyword);
return convertPostsToDto(posts, memberId);
}

public List<PostResponseDto> searchPostsByCategory(Category category, String email) {
Member member = getMemberByEmail(email);
Long memberId = member.getId();
List<Post> posts = postRepository.findByCategory(category);
return convertPostsToDto(posts, memberId);
}

public List<PostResponseDto> sortPostsByCreated(String email) {
Member member = getMemberByEmail(email);
Long memberId = member.getId();
List<Post> posts = postRepository.findAllByOrderByCreatedDesc();
return convertPostsToDto(posts, memberId);
}

public List<PostResponseDto> sortPostsByBuyDate(String email) {
Member member = getMemberByEmail(email);
Long memberId = member.getId();
List<Post> posts = postRepository.findAllByOrderByBuyDateDesc();
return convertPostsToDto(posts, memberId);
}
}

Original file line number Diff line number Diff line change
@@ -1,58 +1,23 @@
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.Post;
import com.SafeNet.Backend.domain.post.exception.PostException;
import com.SafeNet.Backend.domain.post.repository.PostRepository;
import com.SafeNet.Backend.domain.postLike.entity.PostLike;
import com.SafeNet.Backend.domain.postLike.repository.PostLikeRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

@Service
@Transactional(readOnly = true)
@RequiredArgsConstructor
public class MemberItemService {
private final PostRepository postRepository;
private final PostLikeRepository postLikeRepository;
private final MemberRepository memberRepository;
private final CommonPostService commonPostService;

public List<PostResponseDto> getPostsByMemberId(String email) {
Member member = memberRepository.findByEmail(email).orElseThrow(() -> new PostException("Member not found", HttpStatus.NOT_FOUND));
try {
List<Post> posts = postRepository.findByMember_Id(member.getId());
return posts.stream().map(this::convertToDto).collect(Collectors.toList());
} catch (Exception e) {
throw new PostException("Failed to retrieve posts by memberId", HttpStatus.INTERNAL_SERVER_ERROR);
}
return commonPostService.getPostsByMemberId(email);
}

public List<PostResponseDto> getLikedPostsByMemberId(String email) {
Member member = memberRepository.findByEmail(email).orElseThrow(() -> new PostException("Member not found", HttpStatus.NOT_FOUND));
try {
List<PostLike> postLikes = postLikeRepository.findByMember_Id(member.getId());
return postLikes.stream().map(postLike -> this.convertToDto(postLike.getPost())).collect(Collectors.toList());
} catch (Exception e) {
throw new PostException("Failed to retrieve liked posts by memberId", HttpStatus.INTERNAL_SERVER_ERROR);
}
return commonPostService.getLikedPostsByMemberId(email);
}

private PostResponseDto convertToDto(Post post) {
return PostResponseDto.builder()
.postId(post.getId())
.title(post.getTitle())
.likeCount(post.getPostLikeList().size())
.productImageUrl(post.getFileList().isEmpty() ? null : post.getFileList().get(1).getFileUrl())
.count(post.getCount())
.cost(post.getCost())
.build();
}

}
Loading

0 comments on commit 709629c

Please sign in to comment.