Skip to content

Commit

Permalink
Merge pull request #32 from GDSC-DGU/feat/21
Browse files Browse the repository at this point in the history
[feat] 게시글 검색 API
  • Loading branch information
nykoh2001 authored Mar 3, 2024
2 parents d715c0a + 0c5ff77 commit fbd0b07
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -40,4 +41,10 @@ public ApiResponse<?> deletePost(@MemberId Long memberId, @PathVariable Long pos
public ApiResponse<List<PostResponse>> 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));
}
}
Original file line number Diff line number Diff line change
@@ -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<Post, Long> {
default Post findByIdOrThrow(Long id) {
return findById(id).orElseThrow(() -> new CustomException(ErrorMessage.POST_NOT_FOUND));
}

List<Post> findByTitleIsContaining(String title);
}
11 changes: 9 additions & 2 deletions src/main/java/org/harang/server/service/PostService.java
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -77,6 +77,13 @@ public List<PostResponse> getAllPosts() {
.collect(Collectors.toList());
}

public List<PostResponse> 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);
Expand Down

0 comments on commit fbd0b07

Please sign in to comment.