Skip to content

Commit

Permalink
#130 게시글 검색기능 구현
Browse files Browse the repository at this point in the history
  • Loading branch information
thalals committed Dec 20, 2021
1 parent ca79008 commit a5ad83e
Show file tree
Hide file tree
Showing 6 changed files with 110 additions and 23 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -21,4 +21,11 @@ public ResponseEntity<ErrorResponse> errorHandler(IllegalArgumentException e) {
new ErrorResponse(e.getMessage(), 400)
);
}

@ExceptionHandler(value = {NullPointerException.class})
public ResponseEntity<ErrorResponse> errorHandler(NullPointerException e){
return ResponseEntity.badRequest().body(
new ErrorResponse(e.getMessage(), 400)
);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,15 @@ public List<PostResponseDto> getPostList(){

return postList;
}

//검색 리스트
@GetMapping("/posts/search")
public List<PostResponseDto> getSearchList(@RequestParam("category") String category, @RequestParam("keyword") String keyword){
List<Post> searchPostList = postService.getPostSearchList(category, keyword);

return searchPostList.stream().map(post -> modelMapper.map(post, PostResponseDto.class)).collect(Collectors.toList());
}


//조회
@GetMapping("/posts/detail")
Expand Down Expand Up @@ -122,4 +131,6 @@ public boolean checkUserLike(@RequestParam Long id, @AuthenticationPrincipal Use
Long userId = userDetails.getUser().getId();
return postService.checkUserLike(id, userId);
}


}
Original file line number Diff line number Diff line change
@@ -1,11 +1,15 @@
package com.example.marumaru_sparta_verspring.repository;

import com.example.marumaru_sparta_verspring.domain.articles.Post;
import com.example.marumaru_sparta_verspring.domain.user.User;
import org.springframework.data.jpa.repository.JpaRepository;

import java.util.List;


public interface PostRepository extends JpaRepository<Post,Long> {
List<Post> findByUserId(Long userId);
List<Post> findAllByUser(User user);
List<Post> findAllByTitleContainingIgnoreCase(String keyword);
List<Post> findAllByContentContainingIgnoreCase(String keyword);
}
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,7 @@ public String deletePost(Long id, Long userID){
}
}

//게시글 리스트
public List<PostResponseDto> getPostList(){
List<Post> postList = postrepository.findAll();

Expand All @@ -112,6 +113,24 @@ public List<PostResponseDto> getPostList(){
return resultList;
}

//게시글 검색
public List<Post> getPostSearchList(String category, String keyword){
if(category.equals("user")){
User user = userRepository.findByUsername(keyword).orElseThrow(
() -> new NullPointerException("해당 아이디가 존재하지 않습니다.")
);

return postrepository.findAllByUser(user);
}
else if(category.equals("title")){
return postrepository.findAllByTitleContainingIgnoreCase(keyword);
}
else if(category.equals("content")){
return postrepository.findAllByContentContainingIgnoreCase(keyword);
}
return postrepository.findAll();
}

@Transactional
public void createComment(@RequestBody PostCommentRequsetDto postCommentRequsetDto, Long userId){
User user = userRepository.findById(userId).orElseThrow(
Expand Down
76 changes: 53 additions & 23 deletions src/main/resources/static/js/articles/post_list.js
Original file line number Diff line number Diff line change
@@ -1,30 +1,23 @@
$(document).ready(function () {
$('#post-body').empty();
show_post_list();
});

function show_post_list() {
$.ajax({
type: 'GET',
url: '/post-list',
contentType: 'application/json; charset=utf-8',
data: {},
success: function (response) {
const articles = response;
let list_num = 0
if(articles.length>0) {
show_best(articles[0]);
}
for (let i = 1; i < articles.length; i++) {
const username = articles[i]['user']['nickname']
const title = articles[i]['title']
const number = articles[i]['idx']
const contents = articles[i]['content']
const time = formatDate(articles[i]['createdAt'])
const view = articles[i]['view']
const card_img = articles[i]['img']
list_num+=1
function display(articles){
let list_num = 0

for (let i = 0; i < articles.length; i++) {
const username = articles[i]['user']['nickname']
const title = articles[i]['title']
const number = articles[i]['idx']
const contents = articles[i]['content']
const time = formatDate(articles[i]['createdAt'])
const view = articles[i]['view']
const card_img = articles[i]['img']

let temp_html = `
list_num+=1

let temp_html = `
<div onclick="location.href='/posts/detail/${number}'" class="row card-post">
<div class="col-lg-4">
<img class="card-img" src="${card_img}" class="img-fluid rounded-start" alt="pic">
Expand All @@ -41,8 +34,23 @@ function show_post_list() {
</div>
</div>
`
$('#post-body').append(temp_html)
$('#post-body').append(temp_html)
}
}

function show_post_list() {
$.ajax({
type: 'GET',
url: '/post-list',
contentType: 'application/json; charset=utf-8',
data: {},
success: function (response) {
const articles = response;
if(articles.length>0) {
show_best(articles[0]);
articles.shift(); //1번 요소 삭제
}
display(articles);
}
});
}
Expand Down Expand Up @@ -81,4 +89,26 @@ function show_best(best) {
`
$('#post-body').append(temp_html)
}

function postSearch(){
let category = $('#SearchSelect').val();
let keyword = $('#post-search-keyword').val();
$.ajax({
type: 'GET',
url: '/posts/search',
data: {
"category" : category,
"keyword" : keyword
},
success: function (response) {
$('#post-body').empty();
console.log(response)
display(response)
},
error: function (request, status, error) {
console.log(error);
alert(request.responseJSON.message);
}
})
}
16 changes: 16 additions & 0 deletions src/main/resources/templates/articles/post_list.html
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,23 @@ <h5>오늘도 재미있는 소식들이 한가득</h5>
<button src="..." class="btn btn-primary rounded-pill" alt="...">제목</button>
<button src="..." class="btn btn-primary rounded-pill" alt="...">필터</button>
<button onclick="location.href='/posts'" type="button" class="btn btn-dark float-right">게시물 작성</button>

<div class="search-box" style="margin: 2%">
<div class="input-group">
<div style="width: auto">
<select class="form-select" id="SearchSelect" aria-label="Example select with button addon" >
<option value="title">제목</option>
<option value="user">작성자</option>
<option value="content">내용</option>
</select>
</div>
<input type="text" class="form-control" id="post-search-keyword">
<button class="btn btn-outline-secondary" type="button" onclick="postSearch()">검색</button>
</div>
</div>

<hr>

<div id="post-body">
<!-- 게시글 리스트 -->
</div>
Expand Down

0 comments on commit a5ad83e

Please sign in to comment.