함수는 가능하면 한가지 일만 하도록 만들자.
나도 동시에 여러가지를 못하니까.
만약, 책에 대한 키워드 검색을 담당하는 기능을 구현한다고하면 아래와 같이 개발할 것 같다.
물론 검색 기능을 제대로 개발할 경우, 엘라스틱 서치과 같은 검색 엔진을 사용하는게 좋다고 생각하며, 아래 코드는 내가 생각하는 기본적인 코드이자 예시이다.
public BookListWithPageInfoDto searchBooksByKeyword(BookRequestDto bookRequestDto, UserDetailsDto userDetailsDto, String lang) {
List<Long> bookFavoriteIdList = fetchFavoredBookIds(userDetailsDto);
List<String> keywords = processSearchKeywords(bookRequestDto.getKeyword());
List<Long> bookGenreIdList = determineBookGenreIds(keywords);
List<Long> authorIds = fetchAuthorIds(keywords);
Page<Book> books = findBooks(authorIds, keywords, bookGenreIdList, bookRequestDto.getPageable());
List<BookListDto> bookListDto = enrichBookInfoWithFavorites(books, bookFavoriteIdList, lang);
return buildBookResponse(bookListDto, books);
}
private List<Long> fetchFavoredBookIds(UserDetailsDto userDetailsDto) {
return Optional.ofNullable(userDetailsDto)
.map(userDetails -> favoriteRepository.findBookIdsByUserId(userDetails.getId()))
.orElse(Collections.emptyList());
}
private List<String> processSearchKeywords(String searchKeyword) {
return KeywordUtil.removeSingleCharacterKeyword(List.of(searchKeyword.split(" ")));
}
private List<Long> determineBookGenreIds(List<String> keywords) {
if (KeywordUtil.isIncludeFantasy(keywords)) {
return BookGenre.getFantasyGenreIdList();
}
return bookRepository.findGenreIdByKeywordIn(keywords);
}
private List<Long> fetchAuthorIds(List<String> keywords) {
return authorRepository.findIdByKeywordIn(keywords);
}
private Page<Book> findBooks(List<Long> authorIds, List<String> keywords, List<Long> genreIds, Pageable pageable) {
return bookRepository.findByAuthorListOrKeywordList(authorIds, keywords, genreIds, pageable);
}
private List<BookListDto> enrichBookInfoWithFavorites(Page<Book> books, List<Long> favoredBookIds, String lang) {
return Book.addFavoriteInfoToBook(books, favoredBookIds, lang);
}
private BookListWithPageInfoDto buildBookResponse(List<BookListDto> bookList, Page<Book> books) {
return BookListWithPageInfoDto.builder()
.bookList(bookList)
.pageInfo(PageResponseDto.from(books).getPageInfo())
.build();
}
'Etc.' 카테고리의 다른 글
Elasticsearch 다운로드 및 실행 (1) | 2024.01.27 |
---|---|
[Git] 내가 자주 쓰는 명령어 (0) | 2024.01.27 |
[Coding] 의도를 분명하게 하라 (0) | 2024.01.27 |
Git 기본 명령어 (0) | 2023.07.09 |
SSL 인증서 변환(crt, pfx, jks 변환 과정) (0) | 2023.01.05 |