Skip to content

Commit

Permalink
[refactor] 검색 컨트롤러랑 서비스로직 분리
Browse files Browse the repository at this point in the history
  • Loading branch information
Jiwon committed Jul 28, 2023
1 parent 9fd8ecb commit bbb5bf2
Show file tree
Hide file tree
Showing 5 changed files with 255 additions and 223 deletions.
4 changes: 0 additions & 4 deletions src/main/java/shop/hooking/hooking/config/BrandType.java
Original file line number Diff line number Diff line change
Expand Up @@ -36,10 +36,6 @@ public enum BrandType {
this.keyword = keyword;
}

public String getKeyword() {
return keyword;
}

public static boolean containsKeyword(String keyword) {
for (BrandType brandType : BrandType.values()) {
if (brandType.keyword.equals(keyword)) {
Expand Down
9 changes: 3 additions & 6 deletions src/main/java/shop/hooking/hooking/config/MoodType.java
Original file line number Diff line number Diff line change
Expand Up @@ -24,17 +24,14 @@ public enum MoodType {
this.keyword = keyword;
}

public String getKeyword() {
return keyword;
}

public static MoodType fromKeyword(String keyword) {
public static boolean containsKeyword(String keyword) {
for (MoodType moodType : MoodType.values()) {
if (moodType.keyword.equals(keyword)) {
return moodType;
return true;
}
}
return null;
return false;
}
}

250 changes: 77 additions & 173 deletions src/main/java/shop/hooking/hooking/controller/CopyController.java
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,6 @@

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.*;

@Cacheable("copyListCache")
Expand All @@ -43,129 +42,54 @@ public class CopyController {

private final CardJpaRepository cardJpaRepository;

private final BrandRepository brandRepository;



// 전체 카피라이팅 조회
// 페이지네이션 구현
@GetMapping("/{index}") //copy/0=> 0-30 copy/1=>0~30 copy/2=>60~90 copy/9 => 270~300
// 페이지네이션
@GetMapping("/{index}")
public ResponseEntity<HttpRes<List<CopyRes>>> copyList(HttpServletRequest httpRequest, @PathVariable int index) {
Long[] brandIds = {2L, 3L, 4L, 12L, 15L, 17L, 21L, 24L, 25L, 28L};

List<CopyRes> tempCopyRes = new ArrayList<>();

for (Long brandId : brandIds) {
List<CopyRes> copyRes = copyService.getCopyList(brandId); //10개씩 -> 100개
tempCopyRes.addAll(copyRes);
}

// 랜덤
// 브랜드에서 카피 가져오기
List<CopyRes> tempCopyRes = copyService.getCopyResFromBrands();
Collections.shuffle(tempCopyRes);

if (tempCopyRes.isEmpty()) {
String errorMessage = "검색 결과를 찾을 수 없습니다.";
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(null);
}

// 인덱싱
int startIndex = index * 30;
List<CopyRes> resultCopyRes = getLimitedCopyResByIndex(tempCopyRes, startIndex);
setScrapCntWhenTokenNotProvided(httpRequest, resultCopyRes);
List<CopyRes> resultCopyRes = copyService.getLimitedCopyResByIndex(tempCopyRes, startIndex);
copyService.setScrapCntWhenTokenNotProvided(httpRequest, resultCopyRes);
return ResponseEntity.ok(new HttpRes<>(resultCopyRes));
}

}


// 카피라이팅 검색
@GetMapping("/search/{index}")
public ResponseEntity<CopySearchRes> copySearchList(HttpServletRequest httpRequest,
@RequestParam(name = "keyword") String q,
@PathVariable int index) {



CopySearchRes response = new CopySearchRes();
List<CopySearchResult> results = new ArrayList<>();

if (q.isEmpty()) { // 검색 결과가 없다면
response.setCode(HttpStatus.BAD_REQUEST.value());
response.setMessage("검색 결과를 찾을 수 없습니다.");
response.setData(results);
return ResponseEntity.status(HttpStatus.BAD_REQUEST)
.body(response);
}

q = checkKeyword(q);


// 검색 결과 처리 로직...
MoodType moodType = MoodType.fromKeyword(q);
List<CopyRes> moodCopyRes = new ArrayList<>();
List<CopyRes> textCopyRes = new ArrayList<>();
List<CopyRes> brandCopyRes = new ArrayList<>();

textCopyRes = cardJpaRepository.searchCopy(q);

if (moodType != null) {
moodCopyRes = cardJpaRepository.searchMood(q);
setScrapCntWhenTokenNotProvided(httpRequest, moodCopyRes);
Collections.shuffle(moodCopyRes);
results.add(createCopySearchResult("mood", q, moodCopyRes, index));
if (!textCopyRes.isEmpty()) {
setScrapCntWhenTokenNotProvided(httpRequest, textCopyRes);
Collections.shuffle(textCopyRes);
results.add(createCopySearchResult("copy", q, textCopyRes, index));
}
} else if (BrandType.containsKeyword(q)) {
brandCopyRes = cardJpaRepository.searchBrand(q);
setScrapCntWhenTokenNotProvided(httpRequest, brandCopyRes);
Collections.shuffle(brandCopyRes);
results.add(createCopySearchResult("brand", q, brandCopyRes, index));
} else if (!textCopyRes.isEmpty()) {
setScrapCntWhenTokenNotProvided(httpRequest, textCopyRes);
Collections.shuffle(textCopyRes);
results.add(createCopySearchResult("copy", q, textCopyRes, index));
}

// 검색 결과가 없다면
if (results.isEmpty()) {
return getBadRequestResponseEntity(response, results);
CopySearchRes response = copyService.copySearchList(httpRequest, q, index);
if (response.getCode() == HttpStatus.BAD_REQUEST.value()) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(response);
} else {
return ResponseEntity.ok(response);
}


response.setCode(HttpStatus.OK.value());
response.setMessage("요청에 성공하였습니다.");
response.setData(results);

return ResponseEntity.status(HttpStatus.OK)
.body(response);

}



private List<CopyRes> getLimitedCopyResByIndex(List<CopyRes> copyResList, int startIndex) {
int endIndex = Math.min(startIndex + 30, copyResList.size());
return copyResList.subList(startIndex, endIndex);
}




// 카피라이팅 스크랩 가져오기
@CrossOrigin(origins = "https://hooking.shop, https://hooking-dev.netlify.app/, https://hooking.netlify.app/, http://localhost:3000/, http://localhost:3001/")
@GetMapping("/scrap/{index}")
public ResponseEntity<HttpRes<List<CopyRes>>> copyScrapList(HttpServletRequest httpRequest, @PathVariable int index) {
User user = jwtTokenProvider.getUserInfoByToken(httpRequest);
List<CopyRes> copyRes = copyService.getCopyScrapList(user);

int startIndex = index * 30;
List<CopyRes> resultCopyRes = getLimitedCopyResByIndex(copyRes, startIndex);

List<CopyRes> resultCopyRes = copyService.getLimitedCopyResByIndex(copyRes, startIndex);
return ResponseEntity.ok(new HttpRes<>(resultCopyRes));
}



// 카피라이팅 스크랩
@CrossOrigin(origins = "https://hooking.shop, https://hooking-dev.netlify.app/, https://hooking.netlify.app/, http://localhost:3000/, http://localhost:3001/")
@PostMapping("/scrap")
public ResponseEntity<HttpRes<String>> copyScrap(HttpServletRequest httpRequest, @RequestBody CopyReq copyReq) throws IOException {
Expand All @@ -182,105 +106,59 @@ public ResponseEntity<HttpRes<String>> copyScrap(HttpServletRequest httpRequest,
}





// 크롤링 with 파이썬
// @PostMapping("/crawling")
// public HttpRes<String> saveCrawling(@RequestBody CrawlingReq crawlingReq) {
// List<CrawlingData> dataList = crawlingReq.getData();
//
//
// for (CrawlingData data : dataList) {
// String text = data.getText();
// String url = data.getUrl();
// LocalDateTime createdAt = data.getCreatedAt();
// Long brandId = data.getBrandId();
//
//
// Brand brand = brandRepository.findBrandById(brandId);
//
// Card card = new Card();
//
// card.setText(text);
// card.setCreatedAt(createdAt);
// card.setBrand(brand);
// card.setUrl(url);
//
// cardRepository.save(card);
// }
//
// return new HttpRes<>("크롤링 데이터가 저장되었습니다.");
// }

@PostMapping("/crawling")
public HttpRes<String> saveCrawling(@RequestBody CrawlingReq crawlingReq) {
public ResponseEntity<HttpRes<String>> saveCrawling(@RequestBody CrawlingReq crawlingReq) {
List<CrawlingData> dataList = crawlingReq.getData();

copyService.saveCrawlingData(dataList);

for (CrawlingData data : dataList) {
String text = data.getText();
String url = data.getUrl();
LocalDateTime createdAt = data.getCreatedAt();
Long brandId = data.getBrandId();


Brand brand = brandRepository.findBrandById(brandId);

Card card = new Card();

card.setText(text);
card.setCreatedAt(createdAt);
card.setBrand(brand);
card.setUrl(url);

cardRepository.save(card);
}

return new HttpRes<>("크롤링 데이터가 저장되었습니다.");
return ResponseEntity.ok(new HttpRes<>("크롤링 데이터가 저장되었습니다."));
}


// 카피라이팅 필터링
@GetMapping("/filter/{index}")
public ResponseEntity<List<CopyRes>> searchFilterCard(HttpServletRequest httpRequest,@PathVariable int index,CardSearchCondition condition) {
List<CopyRes> results = cardJpaRepository.filter(condition);
int startIndex = index * 30; //인덱싱
List<CopyRes> resultCopyRes = getLimitedCopyResByIndex(results, startIndex);
setScrapCntWhenTokenNotProvided(httpRequest, resultCopyRes);
List<CopyRes> resultCopyRes = copyService.getLimitedCopyResByIndex(results, startIndex);
copyService.setScrapCntWhenTokenNotProvided(httpRequest, resultCopyRes);
if(resultCopyRes.isEmpty()){
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(null);
}
return ResponseEntity.status(HttpStatus.OK).body(resultCopyRes);
}

private String checkKeyword(String q) {
if (q.equals("애프터블로우")) {
q = "애프터 블로우";
}
return q;
}


private void setScrapCntWhenTokenNotProvided(HttpServletRequest httpRequest, List<CopyRes> copyResList) {
String token = httpRequest.getHeader("X-AUTH-TOKEN");
if (token == null) {
for (CopyRes copyRes : copyResList) {
copyRes.setScrapCnt(0);
}
}
}


private CopySearchResult createCopySearchResult(String type, String keyword, List<CopyRes> copyResList, int index) {
CopySearchResult result = new CopySearchResult();
result.setType(type);
result.setKeyword(keyword);
result.setTotalNum(copyResList.size());
result.setData(getLimitedCopyResByIndex(copyResList, index));
return result;
}

private ResponseEntity<CopySearchRes> getBadRequestResponseEntity(CopySearchRes response, List<CopySearchResult> results) {
response.setCode(HttpStatus.BAD_REQUEST.value());
response.setMessage("검색 결과를 찾을 수 없습니다.");
response.setData(results);
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(response);
}



private void setIndicesForCopyRes(List<CopyRes> copyResList, String keyword) {
for (CopyRes copyRes : copyResList) {
String lowercaseText = copyRes.getText().toLowerCase();
int index = lowercaseText.indexOf(keyword.toLowerCase());
List<Integer> indices = new ArrayList<>();
while (index != -1) {
indices.add(index);
index = lowercaseText.indexOf(keyword.toLowerCase(), index + 1);
}
copyRes.setIndex(indices);
}
}

private List<CopyRes> getLimitedCopyRes(List<CopyRes> copyResList, int limit){
Collections.shuffle(copyResList);
int endIndex = Math.min(limit, copyResList.size());
return copyResList.subList(0,endIndex);
}

// 카피라이팅 스크랩 취소 (soft delete)
@PostMapping ("/scrap/cancel")
public ResponseEntity<String> cancelScrap(HttpServletRequest httpRequest, @RequestBody CopyReq copyReq){
User user = jwtTokenProvider.getUserInfoByToken(httpRequest);
Expand All @@ -291,10 +169,36 @@ public ResponseEntity<String> cancelScrap(HttpServletRequest httpRequest, @Reque
return ResponseEntity.status(HttpStatus.OK).body("삭제되었습니다.");
}
else{
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("스크랩 정보가 유효하지 않습니다. ");
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("스크랩 정보가 유효하지 않습니다.");
}

}








// 함수 리팩토링 ...




// private void setIndicesForCopyRes(List<CopyRes> copyResList, String keyword) {
// for (CopyRes copyRes : copyResList) {
// String lowercaseText = copyRes.getText().toLowerCase();
// int index = lowercaseText.indexOf(keyword.toLowerCase());
// List<Integer> indices = new ArrayList<>();
// while (index != -1) {
// indices.add(index);
// index = lowercaseText.indexOf(keyword.toLowerCase(), index + 1);
// }
// copyRes.setIndex(indices);
// }
// }



}
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
@Repository
public interface CardRepository extends JpaRepository<Card, Long>{

List<Card> findTop10ByBrandIdOrderByCreatedAtDesc(Long brandId);
List<Card> findTop6ByBrandIdOrderByCreatedAtDesc(Long brandId);


Card findCardByBrandId(Long brandId); // 브랜드 아이디로 카피라이팅 카드 찾기
Expand Down
Loading

0 comments on commit bbb5bf2

Please sign in to comment.