리팩토링

This commit is contained in:
jinia91
2022-04-14 22:56:36 +09:00
parent c3218a0b8a
commit 6e1ec4c1d8
13 changed files with 82 additions and 138 deletions

View File

@@ -9,16 +9,12 @@ import myblog.blog.shared.application.port.incomming.LayoutRenderingUseCase;
import myblog.blog.article.application.port.incomming.request.ArticleCreateCommand;
import myblog.blog.article.application.port.incomming.request.ArticleEditCommand;
import myblog.blog.article.application.port.incomming.response.ArticleResponseByCategory;
import myblog.blog.article.application.port.incomming.response.ArticleResponseForCardBox;
import myblog.blog.article.application.port.incomming.response.ArticleResponseForEdit;
import myblog.blog.category.appliacation.port.incomming.response.CategoryViewForLayout;
import myblog.blog.member.application.port.incomming.response.PrincipalDetails;
import lombok.RequiredArgsConstructor;
import myblog.blog.shared.utils.MetaTagBuildUtils;
import org.jsoup.Jsoup;
import org.springframework.data.domain.*;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
@@ -28,9 +24,6 @@ import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import static myblog.blog.shared.utils.MarkdownUtils.*;
@Controller
@RequiredArgsConstructor
@@ -59,7 +52,7 @@ public class ArticleController {
Errors errors, Model model) {
if (errors.hasErrors()) getArticleWriteForm(model);
var command = ArticleCreateCommand.from(articleForm, principal.getMemberId());
Long articleId = articleUseCase.writeArticle(command);
var articleId = articleUseCase.writeArticle(command);
articleUseCase.backupArticle(articleId);
tempArticleUseCase.deleteTemp();
return "redirect:/article/view?articleId=" + articleId;
@@ -69,7 +62,7 @@ public class ArticleController {
*/
@GetMapping("/article/edit")
String updateArticle(@RequestParam Long articleId, Model model) {
ArticleResponseForEdit articleDto = articleQueriesUseCase.getArticleForEdit(articleId);
var articleDto = articleQueriesUseCase.getArticleForEdit(articleId);
layoutRenderingUseCase.AddLayoutTo(model);
model.addAttribute("categoryInput", categoryQueriesUseCase.findCategoryByTier(2));
model.addAttribute("tagsInput", tagsQueriesUseCase.findAllTagDtos());
@@ -99,12 +92,11 @@ public class ArticleController {
@RequestParam int tier,
@RequestParam int page,
Model model) {
int totalArticleCnt = getTotalArticleCntByCategory(category, categoryQueriesUseCase.getCategoryViewForLayout());
var pagingBoxHandler =
PagingBoxHandler.createOf(page, getTotalArticleCntByCategory(category, categoryQueriesUseCase.getCategoryViewForLayout()));
PagingBoxHandler.createOf(page, totalArticleCnt);
var articleDtoList = articleQueriesUseCase.getArticlesByCategory(category, tier, pagingBoxHandler.getCurPageNum());
for(var articleDto : articleDtoList){
articleDto.setContent(Jsoup.parse(getHtmlRenderer().render(getParser().parse(articleDto.getContent()))).text());
}
for(var articleDto : articleDtoList) articleDto.parseAndRenderForView();
layoutRenderingUseCase.AddLayoutTo(model);
model.addAttribute("pagingBox", pagingBoxHandler);
model.addAttribute("articleList", articleDtoList);
@@ -112,12 +104,10 @@ public class ArticleController {
}
private int getTotalArticleCntByCategory(String category, CategoryViewForLayout categorys) {
if (categorys.getTitle().equals(category)) return categorys.getCount();
else {
for (var categoryCnt : categorys.getCategoryTCountList()) {
if (categoryCnt.getTitle().equals(category)) return categoryCnt.getCount();
for (var categoryCntSub : categoryCnt.getCategoryTCountList()) {
if (categoryCntSub.getTitle().equals(category)) return categoryCntSub.getCount();
}
for (var categoryCnt : categorys.getCategoryTCountList()) {
if (categoryCnt.getTitle().equals(category)) return categoryCnt.getCount();
for (var categoryCntSub : categoryCnt.getCategoryTCountList()) {
if (categoryCntSub.getTitle().equals(category)) return categoryCntSub.getCount();
}
}
throw new IllegalArgumentException("'"+category+"' 라는 카테고리는 존재하지 않습니다.");
@@ -129,10 +119,8 @@ public class ArticleController {
String getArticlesListByTag(@RequestParam Integer page,
@RequestParam String tagName,
Model model) {
Page<ArticleResponseForCardBox> articleList = articleQueriesUseCase.getArticlesByTag(tagName, page);
for(var article : articleList){
article.parseAndRenderForView();
}
var articleList = articleQueriesUseCase.getArticlesByTag(tagName, page);
for(var article : articleList) article.parseAndRenderForView();
var pagingBoxHandler = PagingBoxHandler.createOf(page, (int)articleList.getTotalElements());
layoutRenderingUseCase.AddLayoutTo(model);
model.addAttribute("articleList", articleList);
@@ -146,10 +134,8 @@ public class ArticleController {
String getArticlesListByKeyword(@RequestParam Integer page,
@RequestParam String keyword,
Model model) {
Page<ArticleResponseForCardBox> articleList = articleQueriesUseCase.getArticlesByKeyword(keyword, page);
for(var article : articleList){
article.parseAndRenderForView();
}
var articleList = articleQueriesUseCase.getArticlesByKeyword(keyword, page);
for(var article : articleList) article.parseAndRenderForView();
var pagingBoxHandler = PagingBoxHandler.createOf(page, (int)articleList.getTotalElements());
layoutRenderingUseCase.AddLayoutTo(model);
model.addAttribute("articleList", articleList);
@@ -173,10 +159,10 @@ public class ArticleController {
addMemberInfoToModel(principal, model);
var articleResponseForDetail = articleQueriesUseCase.getArticleForDetail(articleId);
articleResponseForDetail.parseAndRenderForView();
List<ArticleResponseByCategory> articleTitlesSortByCategory = articleQueriesUseCase
var articleTitlesSortByCategory = articleQueriesUseCase
.getArticlesByCategoryForDetailView(articleResponseForDetail.getCategory());
String metaTags = MetaTagBuildUtils.buildMetaTags(articleResponseForDetail.getTags());
String substringContents = getSubStringContentsFrom(articleResponseForDetail.getContent());
var metaTags = MetaTagBuildUtils.buildMetaTags(articleResponseForDetail.getTags());
var substringContents = getSubStringContentsFrom(articleResponseForDetail.getContent());
layoutRenderingUseCase.AddLayoutTo(model);
model.addAttribute("article", articleResponseForDetail);
model.addAttribute("metaTags",metaTags);

View File

@@ -24,9 +24,7 @@ public class MainController {
*/
@GetMapping("/")
String main(Model model) {
// Dto 전처리
List<ArticleResponseForCardBox> popularArticles = articleQueriesUseCase.getPopularArticles();
//
var popularArticles = articleQueriesUseCase.getPopularArticles();
layoutRenderingUseCase.AddLayoutTo(model);
model.addAttribute("popularArticles", popularArticles);
return "index";
@@ -37,18 +35,8 @@ public class MainController {
*/
@GetMapping("/main/article/{lastArticleId}")
@ResponseBody List<ArticleResponseForCardBox> mainNextPage(@PathVariable(required = false) Long lastArticleId) {
// Entity to Dto
List<ArticleResponseForCardBox> articles = articleQueriesUseCase.getRecentArticles(lastArticleId);
// 화면렌더링을 위한 파싱
for(ArticleResponseForCardBox article : articles){
String content = Jsoup.parse(getHtmlRenderer().render(getParser().parse(article.getContent()))).text();
if(content.length()>300) {
content = content.substring(0, 300);
}
article.setContent(content);
}
var articles = articleQueriesUseCase.getRecentArticles(lastArticleId);
for(var article : articles) article.parseAndRenderForView();
return articles;
}
}

View File

@@ -2,11 +2,9 @@ package myblog.blog.article.adapter.incomming;
import myblog.blog.article.application.port.incomming.TempArticleUseCase;
import myblog.blog.article.application.port.incomming.TempArticleDto;
import myblog.blog.article.domain.TempArticle;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;
import java.util.Optional;
/*
- 임시 게시물 조회, 저장을 위한 rest 컨트롤러
@@ -17,26 +15,14 @@ public class TempArticleController {
private final TempArticleUseCase tempArticleUseCase;
/*
- 임시 아티클 저장 요청
*/
@PostMapping("/article/temp/autoSave")
public String autoSaveTemp(@RequestBody TempArticleDto tempArticleDto){
tempArticleUseCase.saveTemp(new TempArticle(tempArticleDto.getContent()));
tempArticleUseCase.saveTemp(tempArticleDto.getContent());
return "저장성공";
}
/*
- 임시 아티클 조회
*/
@GetMapping("/article/temp/getTemp")
public @ResponseBody
TempArticleDto getTempArticle(){
Optional<TempArticle> tempArticle = tempArticleUseCase.getTempArticle();
TempArticleDto tempArticleDto = new TempArticleDto();
tempArticleDto.setContent(tempArticle.orElse(new TempArticle()).getContent());
return tempArticleDto;
public @ResponseBody TempArticleDto getTempArticle(){
return tempArticleUseCase.getTempArticle();
}
}

View File

@@ -36,9 +36,9 @@ public class ArticleService implements ArticleUseCase {
@Override
@CacheEvict(value = {"layoutCaching", "layoutRecentArticleCaching","seoCaching"}, allEntries = true)
public Long writeArticle(ArticleCreateCommand articleCreateCommand) {
Member writer = memberQueriesUseCase.findById(articleCreateCommand.getMemberId());
Category category = categoryUseCase.findCategory(articleCreateCommand.getCategory());
Article newArticle = new Article(articleCreateCommand.getTitle(),
var writer = memberQueriesUseCase.findById(articleCreateCommand.getMemberId());
var category = categoryUseCase.findCategory(articleCreateCommand.getCategory());
var newArticle = new Article(articleCreateCommand.getTitle(),
articleCreateCommand.getContent(),
articleCreateCommand.getToc(),
writer,
@@ -52,9 +52,9 @@ public class ArticleService implements ArticleUseCase {
@Override
@CacheEvict(value = {"layoutCaching", "layoutRecentArticleCaching","seoCaching"}, allEntries = true)
public void editArticle(ArticleEditCommand articleEditCommand) {
Article article = articleRepositoryPort.findById(articleEditCommand.getArticleId())
var article = articleRepositoryPort.findById(articleEditCommand.getArticleId())
.orElseThrow(() -> new IllegalArgumentException("NotFoundArticleException"));
Category category = categoryUseCase.findCategory(articleEditCommand.getCategoryName());
var category = categoryUseCase.findCategory(articleEditCommand.getCategoryName());
tagUseCase.deleteAllTagsWith(article);
tagUseCase.createNewTagsAndArticleTagList(articleEditCommand.getTags(), article);
article.edit(articleEditCommand.getContent(),
@@ -71,14 +71,14 @@ public class ArticleService implements ArticleUseCase {
@Override
public void backupArticle(Long articleId) {
Article article = articleRepositoryPort.findById(articleId)
var article = articleRepositoryPort.findById(articleId)
.orElseThrow(() -> new IllegalArgumentException("NotFoundArticle"));
articleBackupRepositoryPort.backup(article);
}
@Override
public void addHit(Long articleId) {
Article article = articleRepositoryPort.findById(articleId)
var article = articleRepositoryPort.findById(articleId)
.orElseThrow(() -> new IllegalArgumentException("NotFoundArticleException"));
article.addHit();
}

View File

@@ -19,7 +19,7 @@ public class TagsQueries implements TagsQueriesUseCase {
private final TagRepositoryPort tagRepositoryPort;
public List<TagsResponse> findAllTagDtos(){
List<Tags> tags = tagRepositoryPort.findAll();
var tags = tagRepositoryPort.findAll();
return tags.stream()
.map(tag -> MapperUtils.getModelMapper().map(tag, TagsResponse.class))
.collect(Collectors.toList());

View File

@@ -25,7 +25,7 @@ public class TagsService implements TagUseCase {
public void createNewTagsAndArticleTagList(String names, Article article) {
List<Map<String,String>> tagsDtoArrayList = MapperUtils.getGson().fromJson(names, ArrayList.class);
for (var tagDto : tagsDtoArrayList) {
Tags tag = findOrCreateTagFrom(tagDto);
var tag = findOrCreateTagFrom(tagDto);
articleTagListsRepository.save(new ArticleTagList(article, tag));
}
}

View File

@@ -1,6 +1,7 @@
package myblog.blog.article.application;
import lombok.RequiredArgsConstructor;
import myblog.blog.article.application.port.incomming.TempArticleDto;
import myblog.blog.article.application.port.incomming.TempArticleUseCase;
import myblog.blog.article.application.port.outgoing.TempArticleRepositoryPort;
import myblog.blog.article.domain.TempArticle;
@@ -20,23 +21,28 @@ public class TempArticleService implements TempArticleUseCase {
- 자동 저장 로직
- ID값 고정으로 머지를 작동시켜 임시글 DB에 1개 유지
*/
public void saveTemp(TempArticle tempArticle){
tempArticleRepositoryPort.save(tempArticle);
@Override
public void saveTemp(String tempArticleContents){
tempArticleRepositoryPort.save(new TempArticle(tempArticleContents));
}
/*
- 임시글 가져오기
*/
public Optional<TempArticle> getTempArticle(){
return tempArticleRepositoryPort.findById(1L);
@Override
public TempArticleDto getTempArticle(){
var tempArticle = tempArticleRepositoryPort.findById(1L);
var tempArticleDto = new TempArticleDto();
tempArticleDto.setContent(tempArticle.orElse(new TempArticle()).getContent());
return tempArticleDto;
}
/*
- 임시글 삭제
*/
@Override
public void deleteTemp(){
Optional<TempArticle> deleteArticle = tempArticleRepositoryPort.findById(1L);
var deleteArticle = tempArticleRepositoryPort.findById(1L);
deleteArticle.ifPresent(tempArticleRepositoryPort::delete);
}
}

View File

@@ -1,11 +1,7 @@
package myblog.blog.article.application.port.incomming;
import myblog.blog.article.domain.TempArticle;
import java.util.Optional;
public interface TempArticleUseCase {
void saveTemp(TempArticle tempArticle);
Optional<TempArticle> getTempArticle();
void saveTemp(String tempArticleContents);
TempArticleDto getTempArticle();
void deleteTemp();
}

View File

@@ -23,6 +23,9 @@ public class ArticleResponseForCardBox {
public void parseAndRenderForView(){
this.content = Jsoup.parse(getHtmlRenderer().render(getParser().parse(this.content))).text();
if(content.length()>300) {
content = content.substring(0, 300);
}
}
}

View File

@@ -84,8 +84,7 @@ public class Article extends BasicEntity {
}
private String makeDefaultThumbOf(String thumbnailUrl) {
String defaultThumbUrl = "https://cdn.pixabay.com/photo/2020/11/08/13/28/tree-5723734_1280.jpg";
var defaultThumbUrl = "https://cdn.pixabay.com/photo/2020/11/08/13/28/tree-5723734_1280.jpg";
if (thumbnailUrl == null || thumbnailUrl.equals("")) {
thumbnailUrl = defaultThumbUrl;
}

View File

@@ -31,11 +31,11 @@ public class CategoryController {
@GetMapping("/category/edit")
String editCategoryForm(Model model) {
List<CategorySimpleDto> categoryList = categoryQueriesUseCase.getCategorytCountList();
List<CategorySimpleDto> copyList = new ArrayList<>(List.copyOf(categoryList));
var categoryList = categoryQueriesUseCase.getCategorytCountList();
var copyList = new ArrayList<>(List.copyOf(categoryList));
copyList.remove(0);
CategoryViewForLayout categoryViewForLayout = CategoryViewForLayout.from(categoryList);
List<CommentDtoForLayout> comments = commentQueriesUseCase.recentCommentListForLayout();
var categoryViewForLayout = CategoryViewForLayout.from(categoryList);
var comments = commentQueriesUseCase.recentCommentListForLayout();
model.addAttribute("categoryForEdit", copyList);
model.addAttribute("category", categoryViewForLayout);
@@ -48,7 +48,6 @@ public class CategoryController {
*/
@PostMapping("/category/edit")
@ResponseBody String editCategory(@RequestBody List<CategorySimpleDto> categoryList, Errors errors) {
// List DTO 검증을 위한 커스텀 validator
categorylistValidator.validate(categoryList, errors);
categoryUseCase.changeCategory(categoryList);
return "변경 성공";

View File

@@ -49,68 +49,31 @@ public class CategoryService implements CategoryUseCase {
@Transactional
@CacheEvict(value = {"layoutCaching", "seoCaching"}, allEntries = true)
public void changeCategory(List<CategorySimpleDto> categoryList) {
// 1.카테고리 리스트 순서 작성
CategorySimpleDto.sortByOrder(categoryList);
// 2. 기존 DB 저장된 카테고리 리스트 불러오기
List<Category> categoryListFromDb = categoryRepositoryPort.findAllWithoutDummy();
var categoryListFromDb = categoryRepositoryPort.findAllWithoutDummy();
// 3. 카테고리 변경
while (!categoryList.isEmpty()) {
CategorySimpleDto categorySimpleDto = categoryList.get(0);
var categorySimpleDto = categoryList.get(0);
categoryList.remove(0);
// 부모카테고리인경우
if (categorySimpleDto.getTier() == 1) {
if (categorySimpleDto.isSuperCategory()) {
Category pCategory = null;
// 신규 부모인경우
if (categorySimpleDto.getId() == null) {
pCategory = createNewCategory(categorySimpleDto, null);
}
// 기존 부모인경우
if (categorySimpleDto.isNewCategory()) pCategory = createNewCategory(categorySimpleDto, null);
else {
for (int i = 0; i < categoryListFromDb.size(); i++) {
if (categoryListFromDb.get(i).getId().equals(categorySimpleDto.getId())) {
pCategory = categoryListFromDb.get(i);
categoryListFromDb.remove(i);
break;
}
}
pCategory.updateCategory(
categorySimpleDto.getTitle(),
categorySimpleDto.getTier(),
categorySimpleDto.getPOrder(),
categorySimpleDto.getCOrder(),
null
);
pCategory = findMatchingCategory(categoryListFromDb, categorySimpleDto, pCategory);
pCategory.updateCategory(categorySimpleDto.getTitle(), categorySimpleDto.getTier(), categorySimpleDto.getPOrder(), categorySimpleDto.getCOrder(), null);
}
while (!categoryList.isEmpty()) {
CategorySimpleDto subCategorySimpleDto = categoryList.get(0);
if (subCategorySimpleDto.getTier() == 1) break;
var subCategorySimpleDto = categoryList.get(0);
if (subCategorySimpleDto.isSuperCategory()) break;
categoryList.remove(0);
// 자식 카테고리인경우
Category cCategory = null;
// 카테고리가 기존에 존재 x
if (subCategorySimpleDto.getId() == null) {
cCategory = createNewCategory(subCategorySimpleDto, pCategory.getTitle());
}
// 카테고리가 기존에 존재 o
if (subCategorySimpleDto.isNewCategory()) cCategory = createNewCategory(subCategorySimpleDto, pCategory.getTitle());
else {
for (int i = 0; i < categoryListFromDb.size(); i++) {
if (categoryListFromDb.get(i).getId().equals(subCategorySimpleDto.getId())) {
cCategory = categoryListFromDb.get(i);
categoryListFromDb.remove(i);
break;
}
}
cCategory.updateCategory(
subCategorySimpleDto.getTitle(),
subCategorySimpleDto.getTier(),
subCategorySimpleDto.getPOrder(),
subCategorySimpleDto.getCOrder(),
pCategory);
cCategory = findMatchingCategory(categoryListFromDb, subCategorySimpleDto, cCategory);
cCategory.updateCategory(subCategorySimpleDto.getTitle(), subCategorySimpleDto.getTier(), subCategorySimpleDto.getPOrder(), subCategorySimpleDto.getCOrder(), pCategory);
}
}
}
@@ -118,6 +81,18 @@ public class CategoryService implements CategoryUseCase {
// 3-3 불일치 카테고리 전부 삭제
categoryRepositoryPort.deleteAll(categoryListFromDb);
}
private Category findMatchingCategory(List<Category> categoryListFromDb, CategorySimpleDto categorySimpleDto, Category category) {
for (int i = 0; i < categoryListFromDb.size(); i++) {
if (categoryListFromDb.get(i).getId().equals(categorySimpleDto.getId())) {
category = categoryListFromDb.get(i);
categoryListFromDb.remove(i);
break;
}
}
return category;
}
/*
- 새로운 카테고리 생성하기
- 상위 카테고리 존재 유무 분기

View File

@@ -50,4 +50,10 @@ public class CategorySimpleDto implements Cloneable {
}
}
}
public boolean isSuperCategory(){
return tier == 1;
}
public boolean isNewCategory(){
return id == null;
}
}