diff --git a/src/main/java/org/harang/server/controller/PostController.java b/src/main/java/org/harang/server/controller/PostController.java index e56b698..271046b 100644 --- a/src/main/java/org/harang/server/controller/PostController.java +++ b/src/main/java/org/harang/server/controller/PostController.java @@ -10,6 +10,7 @@ import org.harang.server.dto.response.PostResponse; import org.harang.server.dto.type.SuccessMessage; import org.harang.server.service.PostService; +import org.springframework.transaction.annotation.Transactional; import org.springframework.web.bind.annotation.*; import java.util.List; @@ -40,4 +41,10 @@ public ApiResponse deletePost(@MemberId Long memberId, @PathVariable Long pos public ApiResponse> getAllPosts() { return ApiResponse.success(postService.getAllPosts()); } + + @Transactional(readOnly = true) + @GetMapping("/search") + public ApiResponse getSearchResults(@RequestParam(name = "title") String title) { + return ApiResponse.success(postService.getSearchResults(title)); + } } diff --git a/src/main/java/org/harang/server/repository/PostRepository.java b/src/main/java/org/harang/server/repository/PostRepository.java index bd4919c..fcb5104 100644 --- a/src/main/java/org/harang/server/repository/PostRepository.java +++ b/src/main/java/org/harang/server/repository/PostRepository.java @@ -1,12 +1,16 @@ package org.harang.server.repository; +import java.util.List; import org.harang.server.domain.Post; import org.springframework.data.jpa.repository.JpaRepository; import org.harang.server.dto.type.ErrorMessage; import org.harang.server.exception.CustomException; +import org.springframework.data.jpa.repository.Query; public interface PostRepository extends JpaRepository { default Post findByIdOrThrow(Long id) { return findById(id).orElseThrow(() -> new CustomException(ErrorMessage.POST_NOT_FOUND)); } + + List findByTitleIsContaining(String title); } diff --git a/src/main/java/org/harang/server/service/PostService.java b/src/main/java/org/harang/server/service/PostService.java index f6b1436..4f898c4 100644 --- a/src/main/java/org/harang/server/service/PostService.java +++ b/src/main/java/org/harang/server/service/PostService.java @@ -56,9 +56,9 @@ public Post createPost(Long memberId, PostRequest request) { .build() ); - for (String categoryName: request.categoryList()) { + for (String categoryName : request.categoryList()) { Category category = categoryRepository.findByName(categoryName); - if(category != null) { + if (category != null) { PostCategory savedPostCategory = PostCategory.builder() .post(savedPost) @@ -77,6 +77,13 @@ public List getAllPosts() { .collect(Collectors.toList()); } + public List getSearchResults(String title) { + return postRepository.findByTitleIsContaining(title) + .stream() + .map(p -> PostResponse.of(p)) + .toList(); + } + @Transactional public void deletePost(Long memberId, Long postId) { Post post = postRepository.findByIdOrThrow(postId);