From d5c497ee106c89ec6d18e8a2febd6e0ca3a71e97 Mon Sep 17 00:00:00 2001 From: DaejunBae Date: Sat, 3 Aug 2019 17:09:55 +0900 Subject: [PATCH 01/29] =?UTF-8?q?refactor:=20=ED=8C=A8=ED=82=A4=EC=A7=80?= =?UTF-8?q?=20=EA=B5=AC=EC=A1=B0=20mvc=EB=A1=9C=20=EB=B3=80=EA=B2=BD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../java/techcourse/myblog/config/ErrorConfig.java | 2 +- .../java/techcourse/myblog/config/WebConfig.java | 2 +- .../myblog/{articles => domain}/Article.java | 8 +++----- .../myblog/{articles => domain}/BaseEntity.java | 2 +- .../{articles/comments => domain}/Comment.java | 5 +---- .../techcourse/myblog/{users => domain}/User.java | 7 +++---- .../myblog/{users => domain}/UserValidator.java | 12 ++++++------ .../myblog/{articles => dto}/ArticleDto.java | 7 ++++--- .../{articles/comments => dto}/CommentDto.java | 7 ++++--- .../techcourse/myblog/{users => dto}/UserDto.java | 11 ++++++----- .../{users => exception}/ValidUserException.java | 2 +- .../myblog/interceptor/AuthInterceptor.java | 4 ++-- .../myblog/interceptor/GuestInterceptor.java | 2 +- .../myblog/interceptor/LoginInterceptor.java | 2 +- .../ArticleRepository.java | 3 ++- .../comments => repository}/CommentRepository.java | 5 +++-- .../{users => repository}/UserRepository.java | 3 ++- .../{articles => service}/ArticleService.java | 14 +++++++++++--- .../comments => service}/CommentService.java | 13 ++++++++----- .../myblog/{users => service}/UserService.java | 10 +++++++--- .../{advice => support}/ExceptionAdvice.java | 2 +- .../UserSessionArgumentResolver.java | 5 +++-- .../{articles => web}/ArticleController.java | 8 ++++---- .../comments => web}/CommentController.java | 5 +++-- .../myblog/{index => web}/MainController.java | 6 +++--- .../myblog/{users => web}/UserController.java | 6 ++++-- .../myblog/{users => web}/UserSession.java | 3 ++- src/main/resources/application.properties | 2 +- .../myblog/{articles => domain}/ArticleTest.java | 5 +++-- .../{articles/comments => domain}/CommentTest.java | 5 +++-- .../myblog/{users => domain}/UserTest.java | 3 ++- .../myblog/interceptor/GuestInterceptorTest.java | 4 ++-- .../myblog/interceptor/LoginInterceptorTest.java | 6 +++--- .../{articles => service}/ArticleServiceTest.java | 4 +++- .../comments => service}/CommentServiceTest.java | 12 +++++++----- .../myblog/{users => service}/UserServiceTest.java | 5 ++++- .../{articles => web}/ArticleControllerTests.java | 3 +-- .../myblog/{ => web}/BaseControllerTests.java | 2 +- .../comments => web}/CommentControllerTests.java | 3 +-- .../myblog/{index => web}/MainControllerTests.java | 2 +- .../myblog/{users => web}/UserControllerTests.java | 7 ++++--- 41 files changed, 124 insertions(+), 95 deletions(-) rename src/main/java/techcourse/myblog/{articles => domain}/Article.java (87%) rename src/main/java/techcourse/myblog/{articles => domain}/BaseEntity.java (94%) rename src/main/java/techcourse/myblog/{articles/comments => domain}/Comment.java (87%) rename src/main/java/techcourse/myblog/{users => domain}/User.java (85%) rename src/main/java/techcourse/myblog/{users => domain}/UserValidator.java (60%) rename src/main/java/techcourse/myblog/{articles => dto}/ArticleDto.java (90%) rename src/main/java/techcourse/myblog/{articles/comments => dto}/CommentDto.java (90%) rename src/main/java/techcourse/myblog/{users => dto}/UserDto.java (89%) rename src/main/java/techcourse/myblog/{users => exception}/ValidUserException.java (96%) rename src/main/java/techcourse/myblog/{articles => repository}/ArticleRepository.java (71%) rename src/main/java/techcourse/myblog/{articles/comments => repository}/CommentRepository.java (69%) rename src/main/java/techcourse/myblog/{users => repository}/UserRepository.java (80%) rename src/main/java/techcourse/myblog/{articles => service}/ArticleService.java (85%) rename src/main/java/techcourse/myblog/{articles/comments => service}/CommentService.java (83%) rename src/main/java/techcourse/myblog/{users => service}/UserService.java (84%) rename src/main/java/techcourse/myblog/{advice => support}/ExceptionAdvice.java (97%) rename src/main/java/techcourse/myblog/{users => support}/UserSessionArgumentResolver.java (89%) rename src/main/java/techcourse/myblog/{articles => web}/ArticleController.java (91%) rename src/main/java/techcourse/myblog/{articles/comments => web}/CommentController.java (91%) rename src/main/java/techcourse/myblog/{index => web}/MainController.java (93%) rename src/main/java/techcourse/myblog/{users => web}/UserController.java (93%) rename src/main/java/techcourse/myblog/{users => web}/UserSession.java (86%) rename src/test/java/techcourse/myblog/{articles => domain}/ArticleTest.java (91%) rename src/test/java/techcourse/myblog/{articles/comments => domain}/CommentTest.java (88%) rename src/test/java/techcourse/myblog/{users => domain}/UserTest.java (96%) rename src/test/java/techcourse/myblog/{articles => service}/ArticleServiceTest.java (94%) rename src/test/java/techcourse/myblog/{articles/comments => service}/CommentServiceTest.java (85%) rename src/test/java/techcourse/myblog/{users => service}/UserServiceTest.java (91%) rename src/test/java/techcourse/myblog/{articles => web}/ArticleControllerTests.java (98%) rename src/test/java/techcourse/myblog/{ => web}/BaseControllerTests.java (98%) rename src/test/java/techcourse/myblog/{articles/comments => web}/CommentControllerTests.java (97%) rename src/test/java/techcourse/myblog/{index => web}/MainControllerTests.java (96%) rename src/test/java/techcourse/myblog/{users => web}/UserControllerTests.java (98%) diff --git a/src/main/java/techcourse/myblog/config/ErrorConfig.java b/src/main/java/techcourse/myblog/config/ErrorConfig.java index f29a032f7..6c40f8f7b 100644 --- a/src/main/java/techcourse/myblog/config/ErrorConfig.java +++ b/src/main/java/techcourse/myblog/config/ErrorConfig.java @@ -5,7 +5,7 @@ import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.context.request.WebRequest; -import techcourse.myblog.users.ValidUserException; +import techcourse.myblog.exception.ValidUserException; import java.util.Map; diff --git a/src/main/java/techcourse/myblog/config/WebConfig.java b/src/main/java/techcourse/myblog/config/WebConfig.java index a2b7e41e0..58724d183 100644 --- a/src/main/java/techcourse/myblog/config/WebConfig.java +++ b/src/main/java/techcourse/myblog/config/WebConfig.java @@ -8,7 +8,7 @@ import techcourse.myblog.interceptor.AuthInterceptor; import techcourse.myblog.interceptor.GuestInterceptor; import techcourse.myblog.interceptor.LoginInterceptor; -import techcourse.myblog.users.UserSessionArgumentResolver; +import techcourse.myblog.support.UserSessionArgumentResolver; import java.util.List; diff --git a/src/main/java/techcourse/myblog/articles/Article.java b/src/main/java/techcourse/myblog/domain/Article.java similarity index 87% rename from src/main/java/techcourse/myblog/articles/Article.java rename to src/main/java/techcourse/myblog/domain/Article.java index e9c177891..ffa9786ca 100644 --- a/src/main/java/techcourse/myblog/articles/Article.java +++ b/src/main/java/techcourse/myblog/domain/Article.java @@ -1,12 +1,10 @@ -package techcourse.myblog.articles; +package techcourse.myblog.domain; import lombok.Builder; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; -import techcourse.myblog.articles.comments.Comment; import techcourse.myblog.exception.AuthException; -import techcourse.myblog.users.User; import javax.persistence.*; import java.util.ArrayList; @@ -47,13 +45,13 @@ public List getComments() { return Collections.unmodifiableList(comments); } - void update(Article other) { + public void update(Article other) { this.title = other.title; this.coverUrl = other.coverUrl; this.contents = other.contents; } - boolean isWrittenBy(final Long other) { + public boolean isWrittenBy(final Long other) { if (author.getId().equals(other)) { return true; } diff --git a/src/main/java/techcourse/myblog/articles/BaseEntity.java b/src/main/java/techcourse/myblog/domain/BaseEntity.java similarity index 94% rename from src/main/java/techcourse/myblog/articles/BaseEntity.java rename to src/main/java/techcourse/myblog/domain/BaseEntity.java index e3038bbf3..23b195c63 100644 --- a/src/main/java/techcourse/myblog/articles/BaseEntity.java +++ b/src/main/java/techcourse/myblog/domain/BaseEntity.java @@ -1,4 +1,4 @@ -package techcourse.myblog.articles; +package techcourse.myblog.domain; import lombok.EqualsAndHashCode; import lombok.Getter; diff --git a/src/main/java/techcourse/myblog/articles/comments/Comment.java b/src/main/java/techcourse/myblog/domain/Comment.java similarity index 87% rename from src/main/java/techcourse/myblog/articles/comments/Comment.java rename to src/main/java/techcourse/myblog/domain/Comment.java index 02f3d4264..d63d33156 100644 --- a/src/main/java/techcourse/myblog/articles/comments/Comment.java +++ b/src/main/java/techcourse/myblog/domain/Comment.java @@ -1,13 +1,10 @@ -package techcourse.myblog.articles.comments; +package techcourse.myblog.domain; import lombok.AccessLevel; import lombok.Builder; import lombok.Getter; import lombok.NoArgsConstructor; -import techcourse.myblog.articles.Article; -import techcourse.myblog.articles.BaseEntity; import techcourse.myblog.exception.AuthException; -import techcourse.myblog.users.User; import javax.persistence.*; diff --git a/src/main/java/techcourse/myblog/users/User.java b/src/main/java/techcourse/myblog/domain/User.java similarity index 85% rename from src/main/java/techcourse/myblog/users/User.java rename to src/main/java/techcourse/myblog/domain/User.java index eb6d1a979..7ff58be23 100644 --- a/src/main/java/techcourse/myblog/users/User.java +++ b/src/main/java/techcourse/myblog/domain/User.java @@ -1,7 +1,6 @@ -package techcourse.myblog.users; +package techcourse.myblog.domain; import lombok.*; -import techcourse.myblog.articles.BaseEntity; import javax.persistence.*; @@ -36,11 +35,11 @@ private User(final Long id, final String email, final String name, final String this.password = password; } - boolean authenticate(final String password) { + public boolean authenticate(final String password) { return this.password.equals(password); } - void update(final User other) { + public void update(final User other) { this.name = other.name; } diff --git a/src/main/java/techcourse/myblog/users/UserValidator.java b/src/main/java/techcourse/myblog/domain/UserValidator.java similarity index 60% rename from src/main/java/techcourse/myblog/users/UserValidator.java rename to src/main/java/techcourse/myblog/domain/UserValidator.java index b07ec6ca7..cbc9c7621 100644 --- a/src/main/java/techcourse/myblog/users/UserValidator.java +++ b/src/main/java/techcourse/myblog/domain/UserValidator.java @@ -1,15 +1,15 @@ -package techcourse.myblog.users; +package techcourse.myblog.domain; import java.util.regex.Pattern; public class UserValidator { static final String EMAIL_REGEX = "^[_a-z0-9-]+(.[_a-z0-9-]+)*@(?:\\w+\\.)+\\w+$"; - static final String PASSWORD_REGEX = "^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d)(?=.*[$@$!%*?&])[A-Za-z\\d$@$!%*?&]{8,}"; - static final String NAME_REGEX = "[가-힣ㄱ-ㅎㅏ-ㅣa-zA-Z]{2,10}"; + public static final String PASSWORD_REGEX = "^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d)(?=.*[$@$!%*?&])[A-Za-z\\d$@$!%*?&]{8,}"; + public static final String NAME_REGEX = "[가-힣ㄱ-ㅎㅏ-ㅣa-zA-Z]{2,10}"; - static final String EMAIL_NOT_MATCH_MESSAGE = "메일의 양식을 지켜주세요."; - static final String NAME_NOT_MATCH_MESSAGE = "이름은 2자이상 10자이하이며, 숫자나 특수문자가 포함될 수 없습니다."; - static final String PASSWORD_NOT_MATCH_MESSAGE = "비밀번호는 8자 이상의 소문자,대문자,숫자,특수문자의 조합이여야 합니다."; + public static final String EMAIL_NOT_MATCH_MESSAGE = "메일의 양식을 지켜주세요."; + public static final String NAME_NOT_MATCH_MESSAGE = "이름은 2자이상 10자이하이며, 숫자나 특수문자가 포함될 수 없습니다."; + public static final String PASSWORD_NOT_MATCH_MESSAGE = "비밀번호는 8자 이상의 소문자,대문자,숫자,특수문자의 조합이여야 합니다."; private static final Pattern EMAIL_PATTERN = Pattern.compile(EMAIL_REGEX); private static final Pattern PASSWORD_PATTERN = Pattern.compile(PASSWORD_REGEX); diff --git a/src/main/java/techcourse/myblog/articles/ArticleDto.java b/src/main/java/techcourse/myblog/dto/ArticleDto.java similarity index 90% rename from src/main/java/techcourse/myblog/articles/ArticleDto.java rename to src/main/java/techcourse/myblog/dto/ArticleDto.java index 0e054a449..62febd0b1 100644 --- a/src/main/java/techcourse/myblog/articles/ArticleDto.java +++ b/src/main/java/techcourse/myblog/dto/ArticleDto.java @@ -1,9 +1,10 @@ -package techcourse.myblog.articles; +package techcourse.myblog.dto; import lombok.*; -import techcourse.myblog.articles.comments.Comment; -import techcourse.myblog.users.User; +import techcourse.myblog.domain.Comment; +import techcourse.myblog.domain.Article; +import techcourse.myblog.domain.User; import java.util.List; diff --git a/src/main/java/techcourse/myblog/articles/comments/CommentDto.java b/src/main/java/techcourse/myblog/dto/CommentDto.java similarity index 90% rename from src/main/java/techcourse/myblog/articles/comments/CommentDto.java rename to src/main/java/techcourse/myblog/dto/CommentDto.java index 4455bc270..4adac0f72 100644 --- a/src/main/java/techcourse/myblog/articles/comments/CommentDto.java +++ b/src/main/java/techcourse/myblog/dto/CommentDto.java @@ -1,10 +1,11 @@ -package techcourse.myblog.articles.comments; +package techcourse.myblog.dto; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; -import techcourse.myblog.articles.Article; -import techcourse.myblog.users.User; +import techcourse.myblog.domain.Article; +import techcourse.myblog.domain.Comment; +import techcourse.myblog.domain.User; import java.time.LocalDateTime; diff --git a/src/main/java/techcourse/myblog/users/UserDto.java b/src/main/java/techcourse/myblog/dto/UserDto.java similarity index 89% rename from src/main/java/techcourse/myblog/users/UserDto.java rename to src/main/java/techcourse/myblog/dto/UserDto.java index 341b6e5f9..f14de8ca6 100644 --- a/src/main/java/techcourse/myblog/users/UserDto.java +++ b/src/main/java/techcourse/myblog/dto/UserDto.java @@ -1,12 +1,13 @@ -package techcourse.myblog.users; +package techcourse.myblog.dto; import lombok.*; +import techcourse.myblog.domain.User; import javax.validation.constraints.Email; import javax.validation.constraints.NotBlank; import javax.validation.constraints.Pattern; -import static techcourse.myblog.users.UserValidator.*; +import static techcourse.myblog.domain.UserValidator.*; public class UserDto { @@ -31,11 +32,11 @@ public static class Register { @NotBlank(message = "패스워드 확인을 입력해주세요.") private String confirmPassword; - boolean isValidPassword() { + public boolean isValidPassword() { return password.equals(confirmPassword); } - User toUser() { + public User toUser() { return User.builder() .email(email) .name(name) @@ -73,7 +74,7 @@ public static class Update { @Pattern(regexp = NAME_REGEX, message = NAME_NOT_MATCH_MESSAGE) private String name; - User toUser() { + public User toUser() { return User.builder() .name(name) .id(id) diff --git a/src/main/java/techcourse/myblog/users/ValidUserException.java b/src/main/java/techcourse/myblog/exception/ValidUserException.java similarity index 96% rename from src/main/java/techcourse/myblog/users/ValidUserException.java rename to src/main/java/techcourse/myblog/exception/ValidUserException.java index cf19f1f54..f9c225342 100644 --- a/src/main/java/techcourse/myblog/users/ValidUserException.java +++ b/src/main/java/techcourse/myblog/exception/ValidUserException.java @@ -1,4 +1,4 @@ -package techcourse.myblog.users; +package techcourse.myblog.exception; import org.slf4j.Logger; import org.slf4j.LoggerFactory; diff --git a/src/main/java/techcourse/myblog/interceptor/AuthInterceptor.java b/src/main/java/techcourse/myblog/interceptor/AuthInterceptor.java index 6ab30e941..b0cbea388 100644 --- a/src/main/java/techcourse/myblog/interceptor/AuthInterceptor.java +++ b/src/main/java/techcourse/myblog/interceptor/AuthInterceptor.java @@ -3,13 +3,13 @@ import org.springframework.stereotype.Component; import org.springframework.util.ObjectUtils; import org.springframework.web.servlet.handler.HandlerInterceptorAdapter; -import techcourse.myblog.users.UserSession; +import techcourse.myblog.web.UserSession; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; -import static techcourse.myblog.users.UserSession.USER_SESSION; +import static techcourse.myblog.web.UserSession.USER_SESSION; @Component public class AuthInterceptor extends HandlerInterceptorAdapter { diff --git a/src/main/java/techcourse/myblog/interceptor/GuestInterceptor.java b/src/main/java/techcourse/myblog/interceptor/GuestInterceptor.java index 2eb30344e..36d63280d 100644 --- a/src/main/java/techcourse/myblog/interceptor/GuestInterceptor.java +++ b/src/main/java/techcourse/myblog/interceptor/GuestInterceptor.java @@ -10,7 +10,7 @@ import javax.servlet.http.HttpSession; import java.util.regex.Pattern; -import static techcourse.myblog.users.UserSession.USER_SESSION; +import static techcourse.myblog.web.UserSession.USER_SESSION; @Component public class GuestInterceptor extends HandlerInterceptorAdapter { diff --git a/src/main/java/techcourse/myblog/interceptor/LoginInterceptor.java b/src/main/java/techcourse/myblog/interceptor/LoginInterceptor.java index 0b1522919..c014a5b73 100644 --- a/src/main/java/techcourse/myblog/interceptor/LoginInterceptor.java +++ b/src/main/java/techcourse/myblog/interceptor/LoginInterceptor.java @@ -9,7 +9,7 @@ import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; -import static techcourse.myblog.users.UserSession.USER_SESSION; +import static techcourse.myblog.web.UserSession.USER_SESSION; @Component public class LoginInterceptor extends HandlerInterceptorAdapter { diff --git a/src/main/java/techcourse/myblog/articles/ArticleRepository.java b/src/main/java/techcourse/myblog/repository/ArticleRepository.java similarity index 71% rename from src/main/java/techcourse/myblog/articles/ArticleRepository.java rename to src/main/java/techcourse/myblog/repository/ArticleRepository.java index 786095f91..dbfbe8233 100644 --- a/src/main/java/techcourse/myblog/articles/ArticleRepository.java +++ b/src/main/java/techcourse/myblog/repository/ArticleRepository.java @@ -1,7 +1,8 @@ -package techcourse.myblog.articles; +package techcourse.myblog.repository; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; +import techcourse.myblog.domain.Article; @Repository public interface ArticleRepository extends JpaRepository { diff --git a/src/main/java/techcourse/myblog/articles/comments/CommentRepository.java b/src/main/java/techcourse/myblog/repository/CommentRepository.java similarity index 69% rename from src/main/java/techcourse/myblog/articles/comments/CommentRepository.java rename to src/main/java/techcourse/myblog/repository/CommentRepository.java index c90e05eca..a25431b93 100644 --- a/src/main/java/techcourse/myblog/articles/comments/CommentRepository.java +++ b/src/main/java/techcourse/myblog/repository/CommentRepository.java @@ -1,8 +1,9 @@ -package techcourse.myblog.articles.comments; +package techcourse.myblog.repository; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; -import techcourse.myblog.articles.Article; +import techcourse.myblog.domain.Article; +import techcourse.myblog.domain.Comment; import java.util.List; diff --git a/src/main/java/techcourse/myblog/users/UserRepository.java b/src/main/java/techcourse/myblog/repository/UserRepository.java similarity index 80% rename from src/main/java/techcourse/myblog/users/UserRepository.java rename to src/main/java/techcourse/myblog/repository/UserRepository.java index 6af147aca..04655b9f3 100644 --- a/src/main/java/techcourse/myblog/users/UserRepository.java +++ b/src/main/java/techcourse/myblog/repository/UserRepository.java @@ -1,7 +1,8 @@ -package techcourse.myblog.users; +package techcourse.myblog.repository; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; +import techcourse.myblog.domain.User; import java.util.Optional; diff --git a/src/main/java/techcourse/myblog/articles/ArticleService.java b/src/main/java/techcourse/myblog/service/ArticleService.java similarity index 85% rename from src/main/java/techcourse/myblog/articles/ArticleService.java rename to src/main/java/techcourse/myblog/service/ArticleService.java index 58b2ad0c7..351a0589a 100644 --- a/src/main/java/techcourse/myblog/articles/ArticleService.java +++ b/src/main/java/techcourse/myblog/service/ArticleService.java @@ -1,12 +1,17 @@ -package techcourse.myblog.articles; +package techcourse.myblog.service; import lombok.RequiredArgsConstructor; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; -import techcourse.myblog.users.User; -import techcourse.myblog.users.UserRepository; +import techcourse.myblog.dto.ArticleDto; +import techcourse.myblog.repository.ArticleRepository; +import techcourse.myblog.domain.Article; +import techcourse.myblog.domain.User; +import techcourse.myblog.repository.UserRepository; + +import java.util.List; @Service @Transactional @@ -45,6 +50,9 @@ public Page
findAll(Pageable pageable) { return articleRepository.findAll(pageable); } + public List
findAll(){ + return articleRepository.findAll(); + } @Transactional(readOnly = true) public ArticleDto.Response getOne(Long id) { final Article article = findById(id); diff --git a/src/main/java/techcourse/myblog/articles/comments/CommentService.java b/src/main/java/techcourse/myblog/service/CommentService.java similarity index 83% rename from src/main/java/techcourse/myblog/articles/comments/CommentService.java rename to src/main/java/techcourse/myblog/service/CommentService.java index 58bc5616a..70baab90a 100644 --- a/src/main/java/techcourse/myblog/articles/comments/CommentService.java +++ b/src/main/java/techcourse/myblog/service/CommentService.java @@ -1,12 +1,15 @@ -package techcourse.myblog.articles.comments; +package techcourse.myblog.service; import lombok.RequiredArgsConstructor; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; -import techcourse.myblog.articles.Article; -import techcourse.myblog.articles.ArticleRepository; -import techcourse.myblog.users.User; -import techcourse.myblog.users.UserRepository; +import techcourse.myblog.dto.CommentDto; +import techcourse.myblog.repository.CommentRepository; +import techcourse.myblog.domain.Article; +import techcourse.myblog.repository.ArticleRepository; +import techcourse.myblog.domain.Comment; +import techcourse.myblog.domain.User; +import techcourse.myblog.repository.UserRepository; @Service @Transactional diff --git a/src/main/java/techcourse/myblog/users/UserService.java b/src/main/java/techcourse/myblog/service/UserService.java similarity index 84% rename from src/main/java/techcourse/myblog/users/UserService.java rename to src/main/java/techcourse/myblog/service/UserService.java index 48ee67f93..498636030 100644 --- a/src/main/java/techcourse/myblog/users/UserService.java +++ b/src/main/java/techcourse/myblog/service/UserService.java @@ -1,8 +1,12 @@ -package techcourse.myblog.users; +package techcourse.myblog.service; import lombok.RequiredArgsConstructor; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; +import techcourse.myblog.domain.User; +import techcourse.myblog.repository.UserRepository; +import techcourse.myblog.dto.UserDto; +import techcourse.myblog.exception.ValidUserException; import java.util.List; import java.util.stream.Collectors; @@ -11,8 +15,8 @@ @Transactional @RequiredArgsConstructor public class UserService { - static final String EMAIL_DUPLICATE_MESSAGE = "이미 사용중인 이메일입니다."; - static final String PASSWORD_INVALID_MESSAGE = "비밀번호와 비밀번호 확인이 일치하지 않습니다."; + public static final String EMAIL_DUPLICATE_MESSAGE = "이미 사용중인 이메일입니다."; + public static final String PASSWORD_INVALID_MESSAGE = "비밀번호와 비밀번호 확인이 일치하지 않습니다."; public static final String EMAIL_OR_PASSWORD_NOT_MATCH = "존재하지 않는 이메일 또는 비밀번호가 틀립니다."; private final UserRepository userRepository; diff --git a/src/main/java/techcourse/myblog/advice/ExceptionAdvice.java b/src/main/java/techcourse/myblog/support/ExceptionAdvice.java similarity index 97% rename from src/main/java/techcourse/myblog/advice/ExceptionAdvice.java rename to src/main/java/techcourse/myblog/support/ExceptionAdvice.java index 6040480ef..65feedfef 100644 --- a/src/main/java/techcourse/myblog/advice/ExceptionAdvice.java +++ b/src/main/java/techcourse/myblog/support/ExceptionAdvice.java @@ -1,4 +1,4 @@ -package techcourse.myblog.advice; +package techcourse.myblog.support; import org.slf4j.Logger; import org.slf4j.LoggerFactory; diff --git a/src/main/java/techcourse/myblog/users/UserSessionArgumentResolver.java b/src/main/java/techcourse/myblog/support/UserSessionArgumentResolver.java similarity index 89% rename from src/main/java/techcourse/myblog/users/UserSessionArgumentResolver.java rename to src/main/java/techcourse/myblog/support/UserSessionArgumentResolver.java index 6ae7cc45b..605e1ebc8 100644 --- a/src/main/java/techcourse/myblog/users/UserSessionArgumentResolver.java +++ b/src/main/java/techcourse/myblog/support/UserSessionArgumentResolver.java @@ -1,4 +1,4 @@ -package techcourse.myblog.users; +package techcourse.myblog.support; import org.springframework.core.MethodParameter; import org.springframework.stereotype.Component; @@ -6,11 +6,12 @@ import org.springframework.web.context.request.NativeWebRequest; import org.springframework.web.method.support.HandlerMethodArgumentResolver; import org.springframework.web.method.support.ModelAndViewContainer; +import techcourse.myblog.web.UserSession; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; -import static techcourse.myblog.users.UserSession.USER_SESSION; +import static techcourse.myblog.web.UserSession.USER_SESSION; @Component public class UserSessionArgumentResolver implements HandlerMethodArgumentResolver { diff --git a/src/main/java/techcourse/myblog/articles/ArticleController.java b/src/main/java/techcourse/myblog/web/ArticleController.java similarity index 91% rename from src/main/java/techcourse/myblog/articles/ArticleController.java rename to src/main/java/techcourse/myblog/web/ArticleController.java index 9f95a4c6b..d5b73a432 100644 --- a/src/main/java/techcourse/myblog/articles/ArticleController.java +++ b/src/main/java/techcourse/myblog/web/ArticleController.java @@ -1,14 +1,14 @@ -package techcourse.myblog.articles; +package techcourse.myblog.web; import lombok.RequiredArgsConstructor; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.*; -import techcourse.myblog.articles.comments.Comment; -import techcourse.myblog.users.UserSession; +import techcourse.myblog.dto.ArticleDto; +import techcourse.myblog.service.ArticleService; +import techcourse.myblog.domain.Comment; -import javax.servlet.http.HttpSession; import java.util.List; @Controller diff --git a/src/main/java/techcourse/myblog/articles/comments/CommentController.java b/src/main/java/techcourse/myblog/web/CommentController.java similarity index 91% rename from src/main/java/techcourse/myblog/articles/comments/CommentController.java rename to src/main/java/techcourse/myblog/web/CommentController.java index 3c4611a9a..8ee41ceee 100644 --- a/src/main/java/techcourse/myblog/articles/comments/CommentController.java +++ b/src/main/java/techcourse/myblog/web/CommentController.java @@ -1,11 +1,12 @@ -package techcourse.myblog.articles.comments; +package techcourse.myblog.web; import lombok.RequiredArgsConstructor; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.*; -import techcourse.myblog.users.UserSession; +import techcourse.myblog.dto.CommentDto; +import techcourse.myblog.service.CommentService; @Controller @RequestMapping("/articles/{articleId}/comments") diff --git a/src/main/java/techcourse/myblog/index/MainController.java b/src/main/java/techcourse/myblog/web/MainController.java similarity index 93% rename from src/main/java/techcourse/myblog/index/MainController.java rename to src/main/java/techcourse/myblog/web/MainController.java index d13ec3e3c..122bd7808 100644 --- a/src/main/java/techcourse/myblog/index/MainController.java +++ b/src/main/java/techcourse/myblog/web/MainController.java @@ -1,4 +1,4 @@ -package techcourse.myblog.index; +package techcourse.myblog.web; import lombok.RequiredArgsConstructor; import org.slf4j.Logger; @@ -10,8 +10,8 @@ import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; -import techcourse.myblog.articles.Article; -import techcourse.myblog.articles.ArticleService; +import techcourse.myblog.domain.Article; +import techcourse.myblog.service.ArticleService; import java.util.List; import java.util.stream.Collectors; diff --git a/src/main/java/techcourse/myblog/users/UserController.java b/src/main/java/techcourse/myblog/web/UserController.java similarity index 93% rename from src/main/java/techcourse/myblog/users/UserController.java rename to src/main/java/techcourse/myblog/web/UserController.java index ccc4e7980..de7fb76ad 100644 --- a/src/main/java/techcourse/myblog/users/UserController.java +++ b/src/main/java/techcourse/myblog/web/UserController.java @@ -1,4 +1,4 @@ -package techcourse.myblog.users; +package techcourse.myblog.web; import lombok.RequiredArgsConstructor; import org.slf4j.Logger; @@ -6,12 +6,14 @@ import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.*; +import techcourse.myblog.dto.UserDto; +import techcourse.myblog.service.UserService; import javax.servlet.http.HttpSession; import javax.validation.Valid; import java.util.List; -import static techcourse.myblog.users.UserSession.USER_SESSION; +import static techcourse.myblog.web.UserSession.USER_SESSION; @Controller @RequiredArgsConstructor diff --git a/src/main/java/techcourse/myblog/users/UserSession.java b/src/main/java/techcourse/myblog/web/UserSession.java similarity index 86% rename from src/main/java/techcourse/myblog/users/UserSession.java rename to src/main/java/techcourse/myblog/web/UserSession.java index 02cfc4190..2d3a5fdfe 100644 --- a/src/main/java/techcourse/myblog/users/UserSession.java +++ b/src/main/java/techcourse/myblog/web/UserSession.java @@ -1,6 +1,7 @@ -package techcourse.myblog.users; +package techcourse.myblog.web; import lombok.Getter; +import techcourse.myblog.domain.User; @Getter public class UserSession { diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties index 42e7603cb..b072001dc 100644 --- a/src/main/resources/application.properties +++ b/src/main/resources/application.properties @@ -17,4 +17,4 @@ server.servlet.session.tracking-modes=cookie logging.level.techcourse.myblog=DEBUG # livereload spring.devtools.livereload.enabled=true -spring.thymeleaf.cache=false +spring.thymeleaf.cache=false diff --git a/src/test/java/techcourse/myblog/articles/ArticleTest.java b/src/test/java/techcourse/myblog/domain/ArticleTest.java similarity index 91% rename from src/test/java/techcourse/myblog/articles/ArticleTest.java rename to src/test/java/techcourse/myblog/domain/ArticleTest.java index 060b22279..d935d3800 100644 --- a/src/test/java/techcourse/myblog/articles/ArticleTest.java +++ b/src/test/java/techcourse/myblog/domain/ArticleTest.java @@ -1,9 +1,10 @@ -package techcourse.myblog.articles; +package techcourse.myblog.domain; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import techcourse.myblog.domain.Article; import techcourse.myblog.exception.AuthException; -import techcourse.myblog.users.User; +import techcourse.myblog.domain.User; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.Assertions.assertThrows; diff --git a/src/test/java/techcourse/myblog/articles/comments/CommentTest.java b/src/test/java/techcourse/myblog/domain/CommentTest.java similarity index 88% rename from src/test/java/techcourse/myblog/articles/comments/CommentTest.java rename to src/test/java/techcourse/myblog/domain/CommentTest.java index 2615d334f..a850e564a 100644 --- a/src/test/java/techcourse/myblog/articles/comments/CommentTest.java +++ b/src/test/java/techcourse/myblog/domain/CommentTest.java @@ -1,9 +1,10 @@ -package techcourse.myblog.articles.comments; +package techcourse.myblog.domain; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import techcourse.myblog.domain.Comment; import techcourse.myblog.exception.AuthException; -import techcourse.myblog.users.User; +import techcourse.myblog.domain.User; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.Assertions.assertThrows; diff --git a/src/test/java/techcourse/myblog/users/UserTest.java b/src/test/java/techcourse/myblog/domain/UserTest.java similarity index 96% rename from src/test/java/techcourse/myblog/users/UserTest.java rename to src/test/java/techcourse/myblog/domain/UserTest.java index ef65de887..32facded6 100644 --- a/src/test/java/techcourse/myblog/users/UserTest.java +++ b/src/test/java/techcourse/myblog/domain/UserTest.java @@ -1,4 +1,4 @@ -package techcourse.myblog.users; +package techcourse.myblog.domain; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.DisplayName; @@ -6,6 +6,7 @@ import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; +import techcourse.myblog.domain.User; import java.util.stream.Stream; diff --git a/src/test/java/techcourse/myblog/interceptor/GuestInterceptorTest.java b/src/test/java/techcourse/myblog/interceptor/GuestInterceptorTest.java index e1d4d0409..516563243 100644 --- a/src/test/java/techcourse/myblog/interceptor/GuestInterceptorTest.java +++ b/src/test/java/techcourse/myblog/interceptor/GuestInterceptorTest.java @@ -4,8 +4,8 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.web.reactive.server.WebTestClient; -import techcourse.myblog.users.User; -import techcourse.myblog.users.UserSession; +import techcourse.myblog.domain.User; +import techcourse.myblog.web.UserSession; @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) class GuestInterceptorTest { diff --git a/src/test/java/techcourse/myblog/interceptor/LoginInterceptorTest.java b/src/test/java/techcourse/myblog/interceptor/LoginInterceptorTest.java index e6efe909d..bae4e367b 100644 --- a/src/test/java/techcourse/myblog/interceptor/LoginInterceptorTest.java +++ b/src/test/java/techcourse/myblog/interceptor/LoginInterceptorTest.java @@ -4,10 +4,10 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.web.reactive.server.WebTestClient; -import techcourse.myblog.users.User; -import techcourse.myblog.users.UserSession; +import techcourse.myblog.domain.User; +import techcourse.myblog.web.UserSession; -import static techcourse.myblog.users.UserSession.USER_SESSION; +import static techcourse.myblog.web.UserSession.USER_SESSION; @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) class LoginInterceptorTest { diff --git a/src/test/java/techcourse/myblog/articles/ArticleServiceTest.java b/src/test/java/techcourse/myblog/service/ArticleServiceTest.java similarity index 94% rename from src/test/java/techcourse/myblog/articles/ArticleServiceTest.java rename to src/test/java/techcourse/myblog/service/ArticleServiceTest.java index df840a110..63927a369 100644 --- a/src/test/java/techcourse/myblog/articles/ArticleServiceTest.java +++ b/src/test/java/techcourse/myblog/service/ArticleServiceTest.java @@ -1,4 +1,4 @@ -package techcourse.myblog.articles; +package techcourse.myblog.service; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.DisplayName; @@ -6,6 +6,8 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.transaction.annotation.Transactional; +import techcourse.myblog.dto.ArticleDto; +import techcourse.myblog.service.ArticleService; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.Assertions.assertThrows; diff --git a/src/test/java/techcourse/myblog/articles/comments/CommentServiceTest.java b/src/test/java/techcourse/myblog/service/CommentServiceTest.java similarity index 85% rename from src/test/java/techcourse/myblog/articles/comments/CommentServiceTest.java rename to src/test/java/techcourse/myblog/service/CommentServiceTest.java index 1f96053d0..22be82b0b 100644 --- a/src/test/java/techcourse/myblog/articles/comments/CommentServiceTest.java +++ b/src/test/java/techcourse/myblog/service/CommentServiceTest.java @@ -1,13 +1,15 @@ -package techcourse.myblog.articles.comments; +package techcourse.myblog.service; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; -import techcourse.myblog.articles.ArticleDto; -import techcourse.myblog.articles.ArticleService; -import techcourse.myblog.users.UserDto; -import techcourse.myblog.users.UserService; +import techcourse.myblog.dto.ArticleDto; +import techcourse.myblog.dto.CommentDto; +import techcourse.myblog.service.ArticleService; +import techcourse.myblog.service.CommentService; +import techcourse.myblog.dto.UserDto; +import techcourse.myblog.service.UserService; import static org.assertj.core.api.Assertions.assertThat; diff --git a/src/test/java/techcourse/myblog/users/UserServiceTest.java b/src/test/java/techcourse/myblog/service/UserServiceTest.java similarity index 91% rename from src/test/java/techcourse/myblog/users/UserServiceTest.java rename to src/test/java/techcourse/myblog/service/UserServiceTest.java index 41ca1fb9c..5ac249820 100644 --- a/src/test/java/techcourse/myblog/users/UserServiceTest.java +++ b/src/test/java/techcourse/myblog/service/UserServiceTest.java @@ -1,10 +1,13 @@ -package techcourse.myblog.users; +package techcourse.myblog.service; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; +import techcourse.myblog.domain.User; +import techcourse.myblog.dto.UserDto; +import techcourse.myblog.service.UserService; import java.util.List; diff --git a/src/test/java/techcourse/myblog/articles/ArticleControllerTests.java b/src/test/java/techcourse/myblog/web/ArticleControllerTests.java similarity index 98% rename from src/test/java/techcourse/myblog/articles/ArticleControllerTests.java rename to src/test/java/techcourse/myblog/web/ArticleControllerTests.java index d96ac901e..a020ce64b 100644 --- a/src/test/java/techcourse/myblog/articles/ArticleControllerTests.java +++ b/src/test/java/techcourse/myblog/web/ArticleControllerTests.java @@ -1,4 +1,4 @@ -package techcourse.myblog.articles; +package techcourse.myblog.web; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; @@ -7,7 +7,6 @@ import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.web.reactive.server.WebTestClient; import org.springframework.web.reactive.function.BodyInserters; -import techcourse.myblog.BaseControllerTests; import static org.assertj.core.api.Assertions.assertThat; diff --git a/src/test/java/techcourse/myblog/BaseControllerTests.java b/src/test/java/techcourse/myblog/web/BaseControllerTests.java similarity index 98% rename from src/test/java/techcourse/myblog/BaseControllerTests.java rename to src/test/java/techcourse/myblog/web/BaseControllerTests.java index 338cfef08..dcb50e993 100644 --- a/src/test/java/techcourse/myblog/BaseControllerTests.java +++ b/src/test/java/techcourse/myblog/web/BaseControllerTests.java @@ -1,4 +1,4 @@ -package techcourse.myblog; +package techcourse.myblog.web; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; diff --git a/src/test/java/techcourse/myblog/articles/comments/CommentControllerTests.java b/src/test/java/techcourse/myblog/web/CommentControllerTests.java similarity index 97% rename from src/test/java/techcourse/myblog/articles/comments/CommentControllerTests.java rename to src/test/java/techcourse/myblog/web/CommentControllerTests.java index e991ce3b4..714373f6e 100644 --- a/src/test/java/techcourse/myblog/articles/comments/CommentControllerTests.java +++ b/src/test/java/techcourse/myblog/web/CommentControllerTests.java @@ -1,11 +1,10 @@ -package techcourse.myblog.articles.comments; +package techcourse.myblog.web; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.web.reactive.server.WebTestClient; -import techcourse.myblog.BaseControllerTests; import static org.springframework.web.reactive.function.BodyInserters.fromFormData; diff --git a/src/test/java/techcourse/myblog/index/MainControllerTests.java b/src/test/java/techcourse/myblog/web/MainControllerTests.java similarity index 96% rename from src/test/java/techcourse/myblog/index/MainControllerTests.java rename to src/test/java/techcourse/myblog/web/MainControllerTests.java index 1bb1bedf6..6ffd4e2be 100644 --- a/src/test/java/techcourse/myblog/index/MainControllerTests.java +++ b/src/test/java/techcourse/myblog/web/MainControllerTests.java @@ -1,4 +1,4 @@ -package techcourse.myblog.index; +package techcourse.myblog.web; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; diff --git a/src/test/java/techcourse/myblog/users/UserControllerTests.java b/src/test/java/techcourse/myblog/web/UserControllerTests.java similarity index 98% rename from src/test/java/techcourse/myblog/users/UserControllerTests.java rename to src/test/java/techcourse/myblog/web/UserControllerTests.java index 0a454d6e3..33ca0e721 100644 --- a/src/test/java/techcourse/myblog/users/UserControllerTests.java +++ b/src/test/java/techcourse/myblog/web/UserControllerTests.java @@ -1,4 +1,4 @@ -package techcourse.myblog.users; +package techcourse.myblog.web; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; @@ -11,12 +11,13 @@ import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.web.reactive.server.WebTestClient; import org.springframework.web.reactive.function.BodyInserters; -import techcourse.myblog.BaseControllerTests; +import techcourse.myblog.dto.UserDto; +import techcourse.myblog.service.UserService; import java.util.stream.Stream; import static org.assertj.core.api.Assertions.assertThat; -import static techcourse.myblog.users.UserValidator.*; +import static techcourse.myblog.domain.UserValidator.*; @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) public class UserControllerTests extends BaseControllerTests { From f8f2b08c2ac470674c9cb6c4c5d23aea50ac9752 Mon Sep 17 00:00:00 2001 From: DaejunBae Date: Sat, 3 Aug 2019 19:47:01 +0900 Subject: [PATCH 02/29] =?UTF-8?q?refactor:=20controller=20=ED=8C=A8?= =?UTF-8?q?=ED=82=A4=EC=A7=80=20=EA=B5=AC=EC=A1=B0=20=EB=B3=80=EA=B2=BD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../myblog/web/{ => controller}/ArticleController.java | 3 ++- .../myblog/web/{ => controller}/CommentController.java | 3 ++- .../techcourse/myblog/web/{ => controller}/MainController.java | 2 +- .../techcourse/myblog/web/{ => controller}/UserController.java | 3 ++- .../myblog/web/{ => controller}/ArticleControllerTests.java | 2 +- .../myblog/web/{ => controller}/BaseControllerTests.java | 3 +-- .../myblog/web/{ => controller}/CommentControllerTests.java | 2 +- .../myblog/web/{ => controller}/MainControllerTests.java | 2 +- .../myblog/web/{ => controller}/UserControllerTests.java | 2 +- 9 files changed, 12 insertions(+), 10 deletions(-) rename src/main/java/techcourse/myblog/web/{ => controller}/ArticleController.java (96%) rename src/main/java/techcourse/myblog/web/{ => controller}/CommentController.java (94%) rename src/main/java/techcourse/myblog/web/{ => controller}/MainController.java (97%) rename src/main/java/techcourse/myblog/web/{ => controller}/UserController.java (97%) rename src/test/java/techcourse/myblog/web/{ => controller}/ArticleControllerTests.java (99%) rename src/test/java/techcourse/myblog/web/{ => controller}/BaseControllerTests.java (98%) rename src/test/java/techcourse/myblog/web/{ => controller}/CommentControllerTests.java (98%) rename src/test/java/techcourse/myblog/web/{ => controller}/MainControllerTests.java (95%) rename src/test/java/techcourse/myblog/web/{ => controller}/UserControllerTests.java (99%) diff --git a/src/main/java/techcourse/myblog/web/ArticleController.java b/src/main/java/techcourse/myblog/web/controller/ArticleController.java similarity index 96% rename from src/main/java/techcourse/myblog/web/ArticleController.java rename to src/main/java/techcourse/myblog/web/controller/ArticleController.java index d5b73a432..b3c726b39 100644 --- a/src/main/java/techcourse/myblog/web/ArticleController.java +++ b/src/main/java/techcourse/myblog/web/controller/ArticleController.java @@ -1,4 +1,4 @@ -package techcourse.myblog.web; +package techcourse.myblog.web.controller; import lombok.RequiredArgsConstructor; @@ -8,6 +8,7 @@ import techcourse.myblog.dto.ArticleDto; import techcourse.myblog.service.ArticleService; import techcourse.myblog.domain.Comment; +import techcourse.myblog.web.UserSession; import java.util.List; diff --git a/src/main/java/techcourse/myblog/web/CommentController.java b/src/main/java/techcourse/myblog/web/controller/CommentController.java similarity index 94% rename from src/main/java/techcourse/myblog/web/CommentController.java rename to src/main/java/techcourse/myblog/web/controller/CommentController.java index 8ee41ceee..de1734df1 100644 --- a/src/main/java/techcourse/myblog/web/CommentController.java +++ b/src/main/java/techcourse/myblog/web/controller/CommentController.java @@ -1,4 +1,4 @@ -package techcourse.myblog.web; +package techcourse.myblog.web.controller; import lombok.RequiredArgsConstructor; import org.slf4j.Logger; @@ -7,6 +7,7 @@ import org.springframework.web.bind.annotation.*; import techcourse.myblog.dto.CommentDto; import techcourse.myblog.service.CommentService; +import techcourse.myblog.web.UserSession; @Controller @RequestMapping("/articles/{articleId}/comments") diff --git a/src/main/java/techcourse/myblog/web/MainController.java b/src/main/java/techcourse/myblog/web/controller/MainController.java similarity index 97% rename from src/main/java/techcourse/myblog/web/MainController.java rename to src/main/java/techcourse/myblog/web/controller/MainController.java index 122bd7808..6273a58d8 100644 --- a/src/main/java/techcourse/myblog/web/MainController.java +++ b/src/main/java/techcourse/myblog/web/controller/MainController.java @@ -1,4 +1,4 @@ -package techcourse.myblog.web; +package techcourse.myblog.web.controller; import lombok.RequiredArgsConstructor; import org.slf4j.Logger; diff --git a/src/main/java/techcourse/myblog/web/UserController.java b/src/main/java/techcourse/myblog/web/controller/UserController.java similarity index 97% rename from src/main/java/techcourse/myblog/web/UserController.java rename to src/main/java/techcourse/myblog/web/controller/UserController.java index de7fb76ad..01e34ab9d 100644 --- a/src/main/java/techcourse/myblog/web/UserController.java +++ b/src/main/java/techcourse/myblog/web/controller/UserController.java @@ -1,4 +1,4 @@ -package techcourse.myblog.web; +package techcourse.myblog.web.controller; import lombok.RequiredArgsConstructor; import org.slf4j.Logger; @@ -8,6 +8,7 @@ import org.springframework.web.bind.annotation.*; import techcourse.myblog.dto.UserDto; import techcourse.myblog.service.UserService; +import techcourse.myblog.web.UserSession; import javax.servlet.http.HttpSession; import javax.validation.Valid; diff --git a/src/test/java/techcourse/myblog/web/ArticleControllerTests.java b/src/test/java/techcourse/myblog/web/controller/ArticleControllerTests.java similarity index 99% rename from src/test/java/techcourse/myblog/web/ArticleControllerTests.java rename to src/test/java/techcourse/myblog/web/controller/ArticleControllerTests.java index a020ce64b..0bd25be9f 100644 --- a/src/test/java/techcourse/myblog/web/ArticleControllerTests.java +++ b/src/test/java/techcourse/myblog/web/controller/ArticleControllerTests.java @@ -1,4 +1,4 @@ -package techcourse.myblog.web; +package techcourse.myblog.web.controller; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; diff --git a/src/test/java/techcourse/myblog/web/BaseControllerTests.java b/src/test/java/techcourse/myblog/web/controller/BaseControllerTests.java similarity index 98% rename from src/test/java/techcourse/myblog/web/BaseControllerTests.java rename to src/test/java/techcourse/myblog/web/controller/BaseControllerTests.java index dcb50e993..c2108e331 100644 --- a/src/test/java/techcourse/myblog/web/BaseControllerTests.java +++ b/src/test/java/techcourse/myblog/web/controller/BaseControllerTests.java @@ -1,4 +1,4 @@ -package techcourse.myblog.web; +package techcourse.myblog.web.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; @@ -6,7 +6,6 @@ import static org.springframework.web.reactive.function.BodyInserters.fromFormData; -@SpringBootTest public abstract class BaseControllerTests { protected static final String EMAIL_KEY = "email"; protected static final String USER_NAME_KEY = "name"; diff --git a/src/test/java/techcourse/myblog/web/CommentControllerTests.java b/src/test/java/techcourse/myblog/web/controller/CommentControllerTests.java similarity index 98% rename from src/test/java/techcourse/myblog/web/CommentControllerTests.java rename to src/test/java/techcourse/myblog/web/controller/CommentControllerTests.java index 714373f6e..f3b800f05 100644 --- a/src/test/java/techcourse/myblog/web/CommentControllerTests.java +++ b/src/test/java/techcourse/myblog/web/controller/CommentControllerTests.java @@ -1,4 +1,4 @@ -package techcourse.myblog.web; +package techcourse.myblog.web.controller; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; diff --git a/src/test/java/techcourse/myblog/web/MainControllerTests.java b/src/test/java/techcourse/myblog/web/controller/MainControllerTests.java similarity index 95% rename from src/test/java/techcourse/myblog/web/MainControllerTests.java rename to src/test/java/techcourse/myblog/web/controller/MainControllerTests.java index 6ffd4e2be..a95bcace5 100644 --- a/src/test/java/techcourse/myblog/web/MainControllerTests.java +++ b/src/test/java/techcourse/myblog/web/controller/MainControllerTests.java @@ -1,4 +1,4 @@ -package techcourse.myblog.web; +package techcourse.myblog.web.controller; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; diff --git a/src/test/java/techcourse/myblog/web/UserControllerTests.java b/src/test/java/techcourse/myblog/web/controller/UserControllerTests.java similarity index 99% rename from src/test/java/techcourse/myblog/web/UserControllerTests.java rename to src/test/java/techcourse/myblog/web/controller/UserControllerTests.java index 33ca0e721..ee5f03a78 100644 --- a/src/test/java/techcourse/myblog/web/UserControllerTests.java +++ b/src/test/java/techcourse/myblog/web/controller/UserControllerTests.java @@ -1,4 +1,4 @@ -package techcourse.myblog.web; +package techcourse.myblog.web.controller; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; From 5d80a86dccfd7b320dc99409f8829a2c8ecfa126 Mon Sep 17 00:00:00 2001 From: DaejunBae Date: Sun, 4 Aug 2019 14:22:25 +0900 Subject: [PATCH 03/29] =?UTF-8?q?feat:=20=EC=9E=91=EC=84=B1=EA=B8=80=20?= =?UTF-8?q?=EA=B0=AF=EC=88=98=20=ED=99=95=EC=9D=B8=20api=20=EA=B5=AC?= =?UTF-8?q?=ED=98=84?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../techcourse/myblog/config/WebConfig.java | 1 + .../myblog/repository/ArticleRepository.java | 4 ++ .../myblog/service/ArticleService.java | 21 +++++---- .../myblog/service/UserService.java | 15 ++++-- .../techcourse/myblog/web/api/ArticleApi.java | 30 ++++++++++++ .../myblog/web/api/ArticleApiTest.java | 46 +++++++++++++++++++ 6 files changed, 105 insertions(+), 12 deletions(-) create mode 100644 src/main/java/techcourse/myblog/web/api/ArticleApi.java create mode 100644 src/test/java/techcourse/myblog/web/api/ArticleApiTest.java diff --git a/src/main/java/techcourse/myblog/config/WebConfig.java b/src/main/java/techcourse/myblog/config/WebConfig.java index 58724d183..87a7cb965 100644 --- a/src/main/java/techcourse/myblog/config/WebConfig.java +++ b/src/main/java/techcourse/myblog/config/WebConfig.java @@ -29,6 +29,7 @@ public void addInterceptors(InterceptorRegistry registry) { .addPathPatterns("/users") .addPathPatterns("/users/**") .addPathPatterns("/articles/**") + .addPathPatterns("/api/**") .excludePathPatterns("/users/new") .excludePathPatterns("/users/login"); diff --git a/src/main/java/techcourse/myblog/repository/ArticleRepository.java b/src/main/java/techcourse/myblog/repository/ArticleRepository.java index dbfbe8233..167121122 100644 --- a/src/main/java/techcourse/myblog/repository/ArticleRepository.java +++ b/src/main/java/techcourse/myblog/repository/ArticleRepository.java @@ -3,8 +3,12 @@ import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; import techcourse.myblog.domain.Article; +import techcourse.myblog.domain.User; + +import java.util.List; @Repository public interface ArticleRepository extends JpaRepository { + List
findAllByAuthor(User user); } diff --git a/src/main/java/techcourse/myblog/service/ArticleService.java b/src/main/java/techcourse/myblog/service/ArticleService.java index 351a0589a..4fbefd8c1 100644 --- a/src/main/java/techcourse/myblog/service/ArticleService.java +++ b/src/main/java/techcourse/myblog/service/ArticleService.java @@ -5,11 +5,10 @@ import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; -import techcourse.myblog.dto.ArticleDto; -import techcourse.myblog.repository.ArticleRepository; import techcourse.myblog.domain.Article; import techcourse.myblog.domain.User; -import techcourse.myblog.repository.UserRepository; +import techcourse.myblog.dto.ArticleDto; +import techcourse.myblog.repository.ArticleRepository; import java.util.List; @@ -18,11 +17,10 @@ @RequiredArgsConstructor public class ArticleService { private final ArticleRepository articleRepository; - private final UserRepository userRepository; + private final UserService userService; public Long save(final Long userId, final ArticleDto.Request articleDto) { - User author = userRepository.findById(userId) - .orElseThrow(() -> new IllegalArgumentException("등록된 유저가 아닙니다.")); + User author = userService.getUserById(userId); Article article = articleDto.toArticle(author); @@ -50,9 +48,6 @@ public Page
findAll(Pageable pageable) { return articleRepository.findAll(pageable); } - public List
findAll(){ - return articleRepository.findAll(); - } @Transactional(readOnly = true) public ArticleDto.Response getOne(Long id) { final Article article = findById(id); @@ -76,4 +71,12 @@ private Article findById(Long id) { return articleRepository.findById(id) .orElseThrow(() -> new IllegalArgumentException("없는 글입니다." + id)); } + + public List
findAllByAuthor(String author) { + if(author != null){ + User user = userService.findByEmail(author); + return articleRepository.findAllByAuthor(user); + } + return articleRepository.findAll(); + } } diff --git a/src/main/java/techcourse/myblog/service/UserService.java b/src/main/java/techcourse/myblog/service/UserService.java index 498636030..6d4544c81 100644 --- a/src/main/java/techcourse/myblog/service/UserService.java +++ b/src/main/java/techcourse/myblog/service/UserService.java @@ -4,9 +4,9 @@ import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import techcourse.myblog.domain.User; -import techcourse.myblog.repository.UserRepository; import techcourse.myblog.dto.UserDto; import techcourse.myblog.exception.ValidUserException; +import techcourse.myblog.repository.UserRepository; import java.util.List; import java.util.stream.Collectors; @@ -61,8 +61,7 @@ public List findAllExceptPassword() { } public UserDto.Response findById(Long id) { - User user = userRepository.findById(id) - .orElseThrow(() -> new IllegalArgumentException("존재하지 않는 유저입니다. : " + id)); + User user = getUserById(id); return UserDto.Response.createByUser(user); } @@ -79,6 +78,16 @@ public UserDto.Response update(UserDto.Update userDto) { public void deleteById(Long id) { userRepository.deleteById(id); } + + public User getUserById(final Long id ){ + return userRepository.findById(id) + .orElseThrow(() -> new IllegalArgumentException("존재하지 않는 유저입니다. : " + id)); + } + + public User findByEmail(final String email) { + return userRepository.findByEmail(email) + .orElseThrow(() -> new IllegalArgumentException("존재하지 않는 email 입니다.")); + } } diff --git a/src/main/java/techcourse/myblog/web/api/ArticleApi.java b/src/main/java/techcourse/myblog/web/api/ArticleApi.java new file mode 100644 index 000000000..19b69d59d --- /dev/null +++ b/src/main/java/techcourse/myblog/web/api/ArticleApi.java @@ -0,0 +1,30 @@ +package techcourse.myblog.web.api; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; +import techcourse.myblog.service.ArticleService; + +@RestController +@RequestMapping("/api/articles/counts") +public class ArticleApi { + private static final Logger log = LoggerFactory.getLogger(ArticleApi.class); + + private final ArticleService articleService; + + public ArticleApi(final ArticleService articleService) { + this.articleService = articleService; + } + + @GetMapping + public ResponseEntity getCount(@RequestParam(value = "author", required = false) String author) { + log.debug("author:{}",author); + int count = articleService.findAllByAuthor(author).size(); + return new ResponseEntity<>(count, HttpStatus.FOUND); + } +} diff --git a/src/test/java/techcourse/myblog/web/api/ArticleApiTest.java b/src/test/java/techcourse/myblog/web/api/ArticleApiTest.java new file mode 100644 index 000000000..3957b5a99 --- /dev/null +++ b/src/test/java/techcourse/myblog/web/api/ArticleApiTest.java @@ -0,0 +1,46 @@ +package techcourse.myblog.web.api; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.http.MediaType; +import org.springframework.test.web.reactive.server.WebTestClient; +import techcourse.myblog.web.controller.BaseControllerTests; + +@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) +class ArticleApiTest extends BaseControllerTests { + + @Autowired + WebTestClient webTestClient; + + private String jSessionId; + + @BeforeEach + void setUp() { + final String userPassword = "P@ssw0rd"; + final String userEmail = "emailArticle@gamil.com"; + + addUser("name", userEmail, userPassword); + jSessionId = getJSessionId(userEmail, userPassword); + } + + @Test + void 모든_사용자_작성글_count_확인() { + + webTestClient.get().uri("/api/articles/counts") + .accept(MediaType.APPLICATION_JSON_UTF8) + .cookie(JSESSIONID, jSessionId) + .exchange() + .expectStatus().isFound(); + } + + @Test + void 특정_유저_작성글_count_확인() { + webTestClient.get().uri("/api/articles/counts?author={author}", "asd@asd") + .accept(MediaType.APPLICATION_JSON_UTF8) + .cookie(JSESSIONID, jSessionId) + .exchange() + .expectStatus().isFound(); + } +} \ No newline at end of file From 0b9c209e2b9cee4c5322ef0d9bdebad64920a8bc Mon Sep 17 00:00:00 2001 From: DaejunBae Date: Sun, 4 Aug 2019 14:23:07 +0900 Subject: [PATCH 04/29] =?UTF-8?q?feat:=20=EB=8C=93=EA=B8=80=20=EC=9E=91?= =?UTF-8?q?=EC=84=B1=20api=20=EA=B5=AC=ED=98=84?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../techcourse/myblog/dto/CommentDto.java | 2 + .../myblog/repository/CommentRepository.java | 1 + .../myblog/service/CommentService.java | 28 ++++++++---- .../techcourse/myblog/web/api/CommentApi.java | 37 +++++++++++++++ .../myblog/web/view/CommentResponse.java | 18 ++++++++ src/main/resources/data.sql | 6 +-- .../myblog/service/CommentServiceTest.java | 2 +- .../myblog/web/api/CommentApiTest.java | 45 +++++++++++++++++++ 8 files changed, 127 insertions(+), 12 deletions(-) create mode 100644 src/main/java/techcourse/myblog/web/api/CommentApi.java create mode 100644 src/main/java/techcourse/myblog/web/view/CommentResponse.java create mode 100644 src/test/java/techcourse/myblog/web/api/CommentApiTest.java diff --git a/src/main/java/techcourse/myblog/dto/CommentDto.java b/src/main/java/techcourse/myblog/dto/CommentDto.java index 4adac0f72..0eff264a1 100644 --- a/src/main/java/techcourse/myblog/dto/CommentDto.java +++ b/src/main/java/techcourse/myblog/dto/CommentDto.java @@ -47,12 +47,14 @@ public Comment toComment() { public static class Response { private Long id; private String contents; + private String name; private LocalDateTime modifiedDate; Response(Comment comment) { this.id = comment.getId(); this.contents = comment.getContents(); this.modifiedDate = comment.getModifiedDate(); + this.name = comment.getUser().getName(); } public static Response createByComment(Comment comment) { diff --git a/src/main/java/techcourse/myblog/repository/CommentRepository.java b/src/main/java/techcourse/myblog/repository/CommentRepository.java index a25431b93..2812ccb16 100644 --- a/src/main/java/techcourse/myblog/repository/CommentRepository.java +++ b/src/main/java/techcourse/myblog/repository/CommentRepository.java @@ -1,6 +1,7 @@ package techcourse.myblog.repository; import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Query; import org.springframework.stereotype.Repository; import techcourse.myblog.domain.Article; import techcourse.myblog.domain.Comment; diff --git a/src/main/java/techcourse/myblog/service/CommentService.java b/src/main/java/techcourse/myblog/service/CommentService.java index 70baab90a..472feba43 100644 --- a/src/main/java/techcourse/myblog/service/CommentService.java +++ b/src/main/java/techcourse/myblog/service/CommentService.java @@ -3,14 +3,17 @@ import lombok.RequiredArgsConstructor; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; -import techcourse.myblog.dto.CommentDto; -import techcourse.myblog.repository.CommentRepository; import techcourse.myblog.domain.Article; -import techcourse.myblog.repository.ArticleRepository; import techcourse.myblog.domain.Comment; import techcourse.myblog.domain.User; +import techcourse.myblog.dto.CommentDto; +import techcourse.myblog.repository.ArticleRepository; +import techcourse.myblog.repository.CommentRepository; import techcourse.myblog.repository.UserRepository; +import java.util.List; +import java.util.stream.Collectors; + @Service @Transactional @RequiredArgsConstructor @@ -19,14 +22,14 @@ public class CommentService { private final ArticleRepository articleRepository; private final UserRepository userRepository; - public Long save(final CommentDto.Create commentDto, final Long userId) { + public CommentDto.Response save(final CommentDto.Create commentDto, final Long userId) { final User user = userRepository.findById(userId) .orElseThrow(() -> new IllegalArgumentException("등록된 유저가 아닙니다.")); - final Article article = findArticleById(commentDto.getArticleId()); - final Comment comment = commentDto.toComment(article, user); - - return commentRepository.save(comment).getId(); + Article article = findArticleById(commentDto.getArticleId()); + Comment comment = commentDto.toComment(article, user); + comment = commentRepository.save(comment); + return CommentDto.Response.createByComment(comment); } public CommentDto.Response update(final CommentDto.Update commentDto, final Long userId) { @@ -54,4 +57,13 @@ private Article findArticleById(final Long articleId) { return articleRepository.findById(articleId) .orElseThrow(() -> new IllegalArgumentException("등록된 글이 아닙니다.")); } + + public List findAllByArticleId(final Long articleId) { + //TODO findAllByArticle(article) article 조회 안하는 방법 + Article article = findArticleById(articleId); + List comments = commentRepository.findAllByArticle(article); + return comments.stream() + .map(CommentDto.Response::createByComment) + .collect(Collectors.toList()); + } } diff --git a/src/main/java/techcourse/myblog/web/api/CommentApi.java b/src/main/java/techcourse/myblog/web/api/CommentApi.java new file mode 100644 index 000000000..fe774d0c2 --- /dev/null +++ b/src/main/java/techcourse/myblog/web/api/CommentApi.java @@ -0,0 +1,37 @@ +package techcourse.myblog.web.api; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.*; +import techcourse.myblog.dto.CommentDto; +import techcourse.myblog.service.CommentService; +import techcourse.myblog.web.UserSession; + +import java.util.List; + +@RestController +@RequestMapping("/api/articles/{articleId}/comments") +public class CommentApi { + private static final Logger log = LoggerFactory.getLogger(CommentApi.class); + + private final CommentService commentService; + + public CommentApi(final CommentService commentService) { + this.commentService = commentService; + } + + @PostMapping + public ResponseEntity> create(@PathVariable Long articleId, + @RequestBody CommentDto.Create commentCreate, + UserSession userSession) { + log.debug("contents: {}", commentCreate.getContents()); + + commentCreate.setArticleId(articleId); + commentService.save(commentCreate, userSession.getId()); + + final List comments = commentService.findAllByArticleId(articleId); + return new ResponseEntity<>(comments, HttpStatus.CREATED); + } +} diff --git a/src/main/java/techcourse/myblog/web/view/CommentResponse.java b/src/main/java/techcourse/myblog/web/view/CommentResponse.java new file mode 100644 index 000000000..e3887a596 --- /dev/null +++ b/src/main/java/techcourse/myblog/web/view/CommentResponse.java @@ -0,0 +1,18 @@ +package techcourse.myblog.web.view; + +import lombok.Getter; + +import java.time.LocalDateTime; + +@Getter +public class CommentResponse { + private final Long id; + private final LocalDateTime time; + + public CommentResponse(final Long id) { + this.id = id; + time = LocalDateTime.now(); + } + + +} diff --git a/src/main/resources/data.sql b/src/main/resources/data.sql index 8053265e1..2f3624684 100644 --- a/src/main/resources/data.sql +++ b/src/main/resources/data.sql @@ -21,6 +21,6 @@ INSERT INTO article(user_id, title, cover_url, contents) VALUES (1, '14','https: INSERT INTO article(user_id, title, cover_url, contents) VALUES (1, '15','https://avatars3.githubusercontent.com/u/46308949?s=460&v=4','냉무'); INSERT INTO article(user_id, title, cover_url, contents) VALUES (1, '16','https://avatars3.githubusercontent.com/u/15669435?s=180&v=4','contents'); -INSERT INTO comment(contents, user_id, article_id) VALUES ('contents', 1, 1); -INSERT INTO comment(contents, user_id, article_id) VALUES ('contents', 1, 1); -INSERT INTO comment(contents, user_id, article_id) VALUES ('contents', 1, 1); \ No newline at end of file +INSERT INTO comment(contents, user_id, article_id) VALUES ('contents', 1, 16); +INSERT INTO comment(contents, user_id, article_id) VALUES ('contents', 1, 16); +INSERT INTO comment(contents, user_id, article_id) VALUES ('contents', 1, 16); \ No newline at end of file diff --git a/src/test/java/techcourse/myblog/service/CommentServiceTest.java b/src/test/java/techcourse/myblog/service/CommentServiceTest.java index 22be82b0b..5c70d97c3 100644 --- a/src/test/java/techcourse/myblog/service/CommentServiceTest.java +++ b/src/test/java/techcourse/myblog/service/CommentServiceTest.java @@ -52,7 +52,7 @@ void setUp() { commentDto.setArticleId(articleId); commentDto.setContents("contents"); - commentId = commentService.save(commentDto, userId); + commentId = commentService.save(commentDto, userId).getId(); } @Test diff --git a/src/test/java/techcourse/myblog/web/api/CommentApiTest.java b/src/test/java/techcourse/myblog/web/api/CommentApiTest.java new file mode 100644 index 000000000..8208ac7bf --- /dev/null +++ b/src/test/java/techcourse/myblog/web/api/CommentApiTest.java @@ -0,0 +1,45 @@ +package techcourse.myblog.web.api; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.http.MediaType; +import org.springframework.test.web.reactive.server.WebTestClient; +import reactor.core.publisher.Mono; +import techcourse.myblog.dto.CommentDto; +import techcourse.myblog.web.controller.BaseControllerTests; + +@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) +class CommentApiTest extends BaseControllerTests { + @Autowired + WebTestClient webTestClient; + + private String jSessionId; + + @BeforeEach + void setUp() { + final String userPassword = "P@ssw0rd"; + final String userEmail = "emailArticle@gamil.com"; + + addUser("name", userEmail, userPassword); + jSessionId = getJSessionId(userEmail, userPassword); + } + + @Test + public void create() { + + final String contents = "changed contents"; + CommentDto.Create commentDto = new CommentDto.Create(); + commentDto.setContents(contents); + + webTestClient.post().uri("/api/articles/1/comments") + .contentType(MediaType.APPLICATION_JSON_UTF8) + .accept(MediaType.APPLICATION_JSON_UTF8) + .cookie(JSESSIONID, jSessionId) + .body(Mono.just(commentDto), CommentDto.Create.class) + .exchange() + .expectStatus().isCreated() + .expectHeader().contentType(MediaType.APPLICATION_JSON_UTF8); + } +} \ No newline at end of file From 219b125614025d5e6e0259d860c7ce304602ebcb Mon Sep 17 00:00:00 2001 From: DaejunBae Date: Sun, 4 Aug 2019 14:38:45 +0900 Subject: [PATCH 05/29] =?UTF-8?q?refactor:=20service=20layer,=20=EB=8B=A4?= =?UTF-8?q?=EB=A5=B8=20service=20=EC=9D=98=EC=A1=B4=ED=95=98=EA=B2=8C=20?= =?UTF-8?q?=EB=B3=80=EA=B2=BD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../myblog/service/ArticleService.java | 15 ++++++--- .../myblog/service/CommentService.java | 31 +++++++++---------- .../myblog/service/UserService.java | 29 +++++++++-------- .../myblog/web/controller/UserController.java | 4 +-- .../myblog/service/UserServiceTest.java | 3 +- 5 files changed, 45 insertions(+), 37 deletions(-) diff --git a/src/main/java/techcourse/myblog/service/ArticleService.java b/src/main/java/techcourse/myblog/service/ArticleService.java index 4fbefd8c1..330329ccb 100644 --- a/src/main/java/techcourse/myblog/service/ArticleService.java +++ b/src/main/java/techcourse/myblog/service/ArticleService.java @@ -14,13 +14,18 @@ @Service @Transactional -@RequiredArgsConstructor public class ArticleService { - private final ArticleRepository articleRepository; private final UserService userService; + private final ArticleRepository articleRepository; + + public ArticleService(final UserService userService, final ArticleRepository articleRepository) { + this.userService = userService; + this.articleRepository = articleRepository; + } + public Long save(final Long userId, final ArticleDto.Request articleDto) { - User author = userService.getUserById(userId); + User author = userService.findById(userId); Article article = articleDto.toArticle(author); @@ -67,11 +72,13 @@ public ArticleDto.Response getOne(final Long userId, final Long articleId) { return articleDto; } - private Article findById(Long id) { + @Transactional(readOnly = true) + public Article findById(Long id) { return articleRepository.findById(id) .orElseThrow(() -> new IllegalArgumentException("없는 글입니다." + id)); } + @Transactional(readOnly = true) public List
findAllByAuthor(String author) { if(author != null){ User user = userService.findByEmail(author); diff --git a/src/main/java/techcourse/myblog/service/CommentService.java b/src/main/java/techcourse/myblog/service/CommentService.java index 472feba43..ed93716b5 100644 --- a/src/main/java/techcourse/myblog/service/CommentService.java +++ b/src/main/java/techcourse/myblog/service/CommentService.java @@ -1,34 +1,36 @@ package techcourse.myblog.service; -import lombok.RequiredArgsConstructor; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import techcourse.myblog.domain.Article; import techcourse.myblog.domain.Comment; import techcourse.myblog.domain.User; import techcourse.myblog.dto.CommentDto; -import techcourse.myblog.repository.ArticleRepository; import techcourse.myblog.repository.CommentRepository; -import techcourse.myblog.repository.UserRepository; import java.util.List; import java.util.stream.Collectors; @Service @Transactional -@RequiredArgsConstructor public class CommentService { + private final ArticleService articleService; + private final UserService userService; + private final CommentRepository commentRepository; - private final ArticleRepository articleRepository; - private final UserRepository userRepository; - public CommentDto.Response save(final CommentDto.Create commentDto, final Long userId) { - final User user = userRepository.findById(userId) - .orElseThrow(() -> new IllegalArgumentException("등록된 유저가 아닙니다.")); + public CommentService(final ArticleService articleService, final UserService userService, final CommentRepository commentRepository) { + this.articleService = articleService; + this.userService = userService; + this.commentRepository = commentRepository; + } - Article article = findArticleById(commentDto.getArticleId()); + public CommentDto.Response save(final CommentDto.Create commentDto, final Long userId) { + final User user = userService.findById(userId); + final Article article = articleService.findById(commentDto.getArticleId()); Comment comment = commentDto.toComment(article, user); comment = commentRepository.save(comment); + return CommentDto.Response.createByComment(comment); } @@ -53,15 +55,12 @@ private Comment findCommentById(final Long commentId) { .orElseThrow(() -> new IllegalArgumentException("등록된 댓글이 아닙니다.")); } - private Article findArticleById(final Long articleId) { - return articleRepository.findById(articleId) - .orElseThrow(() -> new IllegalArgumentException("등록된 글이 아닙니다.")); - } + @Transactional(readOnly = true) public List findAllByArticleId(final Long articleId) { //TODO findAllByArticle(article) article 조회 안하는 방법 - Article article = findArticleById(articleId); - List comments = commentRepository.findAllByArticle(article); + final Article article = articleService.findById(articleId); + final List comments = commentRepository.findAllByArticle(article); return comments.stream() .map(CommentDto.Response::createByComment) .collect(Collectors.toList()); diff --git a/src/main/java/techcourse/myblog/service/UserService.java b/src/main/java/techcourse/myblog/service/UserService.java index 6d4544c81..77a09c829 100644 --- a/src/main/java/techcourse/myblog/service/UserService.java +++ b/src/main/java/techcourse/myblog/service/UserService.java @@ -1,6 +1,5 @@ package techcourse.myblog.service; -import lombok.RequiredArgsConstructor; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import techcourse.myblog.domain.User; @@ -9,11 +8,11 @@ import techcourse.myblog.repository.UserRepository; import java.util.List; +import java.util.Optional; import java.util.stream.Collectors; @Service @Transactional -@RequiredArgsConstructor public class UserService { public static final String EMAIL_DUPLICATE_MESSAGE = "이미 사용중인 이메일입니다."; public static final String PASSWORD_INVALID_MESSAGE = "비밀번호와 비밀번호 확인이 일치하지 않습니다."; @@ -21,11 +20,15 @@ public class UserService { private final UserRepository userRepository; + public UserService(final UserRepository userRepository) { + this.userRepository = userRepository; + } + public Long save(UserDto.Register userDto) { verifyDuplicateEmail(userDto.getEmail()); verifyPassword(userDto); - User user = userDto.toUser(); + final User user = userDto.toUser(); return userRepository.save(user).getId(); } @@ -42,33 +45,33 @@ private void verifyDuplicateEmail(String email) { } } + @Transactional(readOnly = true) public User login(UserDto.Register userDto) { - User user = userRepository.findByEmail(userDto.getEmail()) - .orElseThrow(() -> new ValidUserException(EMAIL_OR_PASSWORD_NOT_MATCH, "password")); + final Optional user = userRepository.findByEmail(userDto.getEmail()); - if (!user.authenticate(userDto.getPassword())) { + if (!user.isPresent() || !user.get().authenticate(userDto.getPassword())) { throw new ValidUserException(EMAIL_OR_PASSWORD_NOT_MATCH, "password"); } - return user; + return user.get(); } public List findAllExceptPassword() { - List users = userRepository.findAll(); + final List users = userRepository.findAll(); + return users.stream() .map(UserDto.Response::createByUser) .collect(Collectors.toList()); } - public UserDto.Response findById(Long id) { - User user = getUserById(id); + public UserDto.Response getUserById(Long id) { + final User user = findById(id); return UserDto.Response.createByUser(user); } public UserDto.Response update(UserDto.Update userDto) { - User user = userRepository.findById(userDto.getId()) - .orElseThrow(() -> new IllegalArgumentException("존재하지 않는 유저입니다. : " + userDto.getId())); + final User user = findById(userDto.getId()); user.update(userDto.toUser()); @@ -79,7 +82,7 @@ public void deleteById(Long id) { userRepository.deleteById(id); } - public User getUserById(final Long id ){ + public User findById(final Long id) { return userRepository.findById(id) .orElseThrow(() -> new IllegalArgumentException("존재하지 않는 유저입니다. : " + id)); } diff --git a/src/main/java/techcourse/myblog/web/controller/UserController.java b/src/main/java/techcourse/myblog/web/controller/UserController.java index 01e34ab9d..86026ee25 100644 --- a/src/main/java/techcourse/myblog/web/controller/UserController.java +++ b/src/main/java/techcourse/myblog/web/controller/UserController.java @@ -69,14 +69,14 @@ public String userList(Model model) { @GetMapping("/{id}") public String show(@PathVariable Long id, Model model) { - UserDto.Response userResponseDto = userService.findById(id); + UserDto.Response userResponseDto = userService.getUserById(id); model.addAttribute("user", userResponseDto); return "mypage"; } @GetMapping("/{id}/edit") public String editForm(@PathVariable Long id, Model model) { - UserDto.Response userResponseDto = userService.findById(id); + UserDto.Response userResponseDto = userService.getUserById(id); model.addAttribute("user", userResponseDto); return "mypage-edit"; } diff --git a/src/test/java/techcourse/myblog/service/UserServiceTest.java b/src/test/java/techcourse/myblog/service/UserServiceTest.java index 5ac249820..3e3d0c6d3 100644 --- a/src/test/java/techcourse/myblog/service/UserServiceTest.java +++ b/src/test/java/techcourse/myblog/service/UserServiceTest.java @@ -7,7 +7,6 @@ import org.springframework.boot.test.context.SpringBootTest; import techcourse.myblog.domain.User; import techcourse.myblog.dto.UserDto; -import techcourse.myblog.service.UserService; import java.util.List; @@ -46,7 +45,7 @@ void findAllExceptPassword() { @Test void findById() { - final UserDto.Response expected = userService.findById(id); + final UserDto.Response expected = userService.getUserById(id); assertEquals(register.getName(), expected.getName()); } From 5b8ff0875c6b93843674535917789cac2cfc1308 Mon Sep 17 00:00:00 2001 From: DaejunBae Date: Sun, 4 Aug 2019 18:49:54 +0900 Subject: [PATCH 06/29] =?UTF-8?q?refactor:=20ArticleServiceTest=20Mockito?= =?UTF-8?q?=20=EB=A1=9C=20=EA=B5=AC=ED=98=84?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../java/techcourse/myblog/domain/User.java | 2 +- .../myblog/service/ArticleServiceTest.java | 171 ++++++++++++++---- 2 files changed, 135 insertions(+), 38 deletions(-) diff --git a/src/main/java/techcourse/myblog/domain/User.java b/src/main/java/techcourse/myblog/domain/User.java index 7ff58be23..962fa6ab6 100644 --- a/src/main/java/techcourse/myblog/domain/User.java +++ b/src/main/java/techcourse/myblog/domain/User.java @@ -23,7 +23,7 @@ public class User extends BaseEntity { private String password; @Builder - private User(final Long id, final String email, final String name, final String password) { + public User(final Long id, final String email, final String name, final String password) { if (id == null) { UserValidator.validateEmail(email); UserValidator.validatePassword(password); diff --git a/src/test/java/techcourse/myblog/service/ArticleServiceTest.java b/src/test/java/techcourse/myblog/service/ArticleServiceTest.java index 63927a369..f3b9ba49f 100644 --- a/src/test/java/techcourse/myblog/service/ArticleServiceTest.java +++ b/src/test/java/techcourse/myblog/service/ArticleServiceTest.java @@ -1,67 +1,164 @@ package techcourse.myblog.service; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.transaction.annotation.Transactional; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; +import org.springframework.test.context.junit.jupiter.SpringExtension; +import techcourse.myblog.domain.Article; +import techcourse.myblog.domain.User; import techcourse.myblog.dto.ArticleDto; -import techcourse.myblog.service.ArticleService; +import techcourse.myblog.exception.AuthException; +import techcourse.myblog.repository.ArticleRepository; + +import java.util.List; +import java.util.Optional; import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.Mockito.*; -@Transactional -@SpringBootTest +@ExtendWith(SpringExtension.class) class ArticleServiceTest { + private static final long ARTICLE_ID = 1L; + private static final Long USER_ID = 1L; - @Autowired + @InjectMocks ArticleService articleService; - private ArticleDto.Response articleDto; - private long userId = 1L; + @Mock + UserService userService; + + @Mock + ArticleRepository articleRepository; + + private User user = new User(USER_ID, "email@gamil.com", "name", "P@ssw0rd"); + private ArticleDto.Request articleRequest = new ArticleDto.Request(ARTICLE_ID, "contents", "title", "coverUrl"); + private Article article = articleRequest.toArticle(user); + + @Test + void 게시글_저장() { + // given + when(userService.findById(USER_ID)).thenReturn(user); + when(articleRepository.save(article)).thenReturn(article); + + // when + articleService.save(USER_ID, articleRequest); + + // then + verify(articleRepository).save(article); + } + + @Test + void 존재하는_게시글_조회() { + // given + when(articleRepository.findById(ARTICLE_ID)).thenReturn(Optional.ofNullable(article)); + + // when + articleService.findById(ARTICLE_ID); + + // then + verify(articleRepository).findById(ARTICLE_ID); + } + + @Test + void 존재하지_않는_게시글_조회_예외처리() { + // given + final long articleId = 100L; + when(articleRepository.findById(articleId)).thenThrow(IllegalArgumentException.class); + + // when & then + assertThrows(IllegalArgumentException.class, () -> articleService.findById(articleId)); + verify(articleRepository).findById(articleId); + } + + @Test + void 게시글_수정() { + // given + when(articleRepository.findById(ARTICLE_ID)).thenReturn(Optional.ofNullable(article)); + + // when & then + assertDoesNotThrow(() -> articleService.edit(USER_ID, articleRequest)); + verify(articleRepository).findById(ARTICLE_ID); + } + + @Test + void 다른_작성자_게시글_수정_예외처리() { + // given + when(articleRepository.findById(ARTICLE_ID)).thenReturn(Optional.ofNullable(article)); + + // when & then + assertThrows(AuthException.class, () -> articleService.edit(2L, articleRequest)); + } + + @Test + void 게시글_삭제() { + // given + when(articleRepository.findById(ARTICLE_ID)).thenReturn(Optional.ofNullable(article)); - @BeforeEach - void setUp() { - ArticleDto.Request articleRequest = ArticleDto.Request.builder() - .contents("contents") - .coverUrl("coverUrl") - .title("title") - .build(); + // when + articleService.deleteById(USER_ID, ARTICLE_ID); - Long id = articleService.save(userId, articleRequest); - articleDto = articleService.getOne(id); + // then + verify(articleRepository).deleteById(ARTICLE_ID); } @Test - void findById() { - assertThat(articleService.getOne(articleDto.getId())).isNotNull(); + void 다른_작성자_게시글_삭제_예외처리() { + // given + when(articleRepository.findById(ARTICLE_ID)).thenReturn(Optional.ofNullable(article)); + + // when & then + assertThrows(AuthException.class, () -> articleService.deleteById(10L, ARTICLE_ID)); + verify(articleRepository, never()).deleteById(ARTICLE_ID); } @Test - @DisplayName("getOne 없는 id로 검색했을 경우 예외처리") - void findById_예외처리() { - assertThrows(IllegalArgumentException.class, () -> articleService.getOne(Long.MAX_VALUE)); + void Article_페이지_조회() { + // given + Pageable pageable = mock(Pageable.class); + Page articles = mock(Page.class); + when(articleRepository.findAll(pageable)).thenReturn(articles); + + // when + Page
expected = articleService.findAll(pageable); + + // then + verify(articleRepository).findAll(pageable); + assertThat(articles).isEqualTo(expected); + } + + @Test + void 특정_author_Article_전체_조회(){ + // given + List articles = mock(List.class); + when(articleRepository.findAllByAuthor(user)).thenReturn(articles); + when(userService.findByEmail(user.getEmail())).thenReturn(user); + + // when + List
expected = articleService.findAllByAuthor(user.getEmail()); + + // then + verify(articleRepository, never()).findAll(); + verify(articleRepository).findAllByAuthor(user); + assertThat(articles).isEqualTo(expected); } @Test - void edit() { + void Article_전체_조회(){ // given - final ArticleDto.Request editedArticle = ArticleDto.Request.builder() - .id(articleDto.getId()) - .contents("1") - .coverUrl("2") - .title("3") - .build(); + List articles = mock(List.class); + when(articleRepository.findAll()).thenReturn(articles); // when - Long id = articleService.edit(userId, editedArticle); - ArticleDto.Response expected = articleService.getOne(id); + List
expected = articleService.findAllByAuthor(null); // then - assertThat(editedArticle.getContents()).isEqualTo(expected.getContents()); - assertThat(editedArticle.getCoverUrl()).isEqualTo(expected.getCoverUrl()); - assertThat(editedArticle.getTitle()).isEqualTo(expected.getTitle()); + verify(articleRepository).findAll(); + verify(articleRepository, never()).findAllByAuthor(null); + assertThat(articles).isEqualTo(expected); } } \ No newline at end of file From b59cfb89886925760aa275e323f130f2be888c5f Mon Sep 17 00:00:00 2001 From: DaejunBae Date: Mon, 5 Aug 2019 14:02:39 +0900 Subject: [PATCH 07/29] =?UTF-8?q?feat:=20RollingFileAppender=20=EC=B6=94?= =?UTF-8?q?=EA=B0=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/main/resources/logback-access.xml | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/src/main/resources/logback-access.xml b/src/main/resources/logback-access.xml index 9ca8ad6bd..e314eb610 100644 --- a/src/main/resources/logback-access.xml +++ b/src/main/resources/logback-access.xml @@ -6,4 +6,23 @@ + + + target/log/roll-by-time-and-size/app.log + + + target/log/roll-by-time-and-size/app.%d{yyyy-MM-dd-mm}.%i.log.zip + + 5KB + 20 + 1MB + + + %d{HH:mm:ss.SSS} [%-5level] [%thread] [%logger{36}] - %m%n + + + + + + \ No newline at end of file From adafd6567c9109d17895df982fc906368a6517e3 Mon Sep 17 00:00:00 2001 From: DaejunBae Date: Mon, 5 Aug 2019 16:26:54 +0900 Subject: [PATCH 08/29] =?UTF-8?q?refactor:=20CommentApiTest=20ObjectMapper?= =?UTF-8?q?=20=EC=A0=81=EC=9A=A9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../myblog/web/api/CommentApiTest.java | 24 ++++++++++++++++--- 1 file changed, 21 insertions(+), 3 deletions(-) diff --git a/src/test/java/techcourse/myblog/web/api/CommentApiTest.java b/src/test/java/techcourse/myblog/web/api/CommentApiTest.java index 8208ac7bf..a01b4ac7e 100644 --- a/src/test/java/techcourse/myblog/web/api/CommentApiTest.java +++ b/src/test/java/techcourse/myblog/web/api/CommentApiTest.java @@ -1,20 +1,31 @@ package techcourse.myblog.web.api; +import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.http.MediaType; +import org.springframework.test.web.reactive.server.EntityExchangeResult; import org.springframework.test.web.reactive.server.WebTestClient; import reactor.core.publisher.Mono; import techcourse.myblog.dto.CommentDto; import techcourse.myblog.web.controller.BaseControllerTests; +import java.io.IOException; +import java.util.List; +import java.util.Objects; + +import static org.assertj.core.api.Assertions.assertThat; + @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) class CommentApiTest extends BaseControllerTests { @Autowired WebTestClient webTestClient; + @Autowired + ObjectMapper objectMapper; + private String jSessionId; @BeforeEach @@ -27,19 +38,26 @@ void setUp() { } @Test - public void create() { + public void create() throws IOException { final String contents = "changed contents"; CommentDto.Create commentDto = new CommentDto.Create(); commentDto.setContents(contents); - webTestClient.post().uri("/api/articles/1/comments") + final EntityExchangeResult entityExchangeResult = webTestClient.post().uri("/api/articles/1/comments") .contentType(MediaType.APPLICATION_JSON_UTF8) .accept(MediaType.APPLICATION_JSON_UTF8) .cookie(JSESSIONID, jSessionId) .body(Mono.just(commentDto), CommentDto.Create.class) .exchange() .expectStatus().isCreated() - .expectHeader().contentType(MediaType.APPLICATION_JSON_UTF8); + .expectHeader().contentType(MediaType.APPLICATION_JSON_UTF8) + .expectBody().returnResult(); + + String body = new String(Objects.requireNonNull(entityExchangeResult.getResponseBody())); + + List comments = new ObjectMapper().readValue(body, List.class); + + assertThat(comments).isNotEmpty(); } } \ No newline at end of file From 3671a77692d7843533f567d494f09a01bb326301 Mon Sep 17 00:00:00 2001 From: DaejunBae Date: Mon, 5 Aug 2019 23:07:46 +0900 Subject: [PATCH 09/29] =?UTF-8?q?test:=20CommentServiceTest=20slicesTest?= =?UTF-8?q?=20=EB=A1=9C=20=EA=B5=AC=ED=98=84?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../myblog/service/CommentServiceTest.java | 137 ++++++++++++------ 1 file changed, 95 insertions(+), 42 deletions(-) diff --git a/src/test/java/techcourse/myblog/service/CommentServiceTest.java b/src/test/java/techcourse/myblog/service/CommentServiceTest.java index 5c70d97c3..dcf2e8565 100644 --- a/src/test/java/techcourse/myblog/service/CommentServiceTest.java +++ b/src/test/java/techcourse/myblog/service/CommentServiceTest.java @@ -1,71 +1,124 @@ package techcourse.myblog.service; -import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; -import techcourse.myblog.dto.ArticleDto; +import org.springframework.boot.test.mock.mockito.MockBean; +import techcourse.myblog.domain.Article; +import techcourse.myblog.domain.Comment; +import techcourse.myblog.domain.User; import techcourse.myblog.dto.CommentDto; -import techcourse.myblog.service.ArticleService; -import techcourse.myblog.service.CommentService; -import techcourse.myblog.dto.UserDto; -import techcourse.myblog.service.UserService; +import techcourse.myblog.exception.AuthException; +import techcourse.myblog.repository.CommentRepository; + +import java.util.Optional; import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.*; -@SpringBootTest +@SpringBootTest(classes = CommentService.class) class CommentServiceTest { - @Autowired - CommentService commentService; + private static final long USER_ID = 1L; + protected static final long ANOTHER_USER_ID = 2L; @Autowired - UserService userService; + CommentService commentService; - @Autowired + @MockBean ArticleService articleService; - private Long userId; - private Long articleId; - private Long commentId; - - @BeforeEach - void setUp() { - UserDto.Register userDto = UserDto.Register.builder() - .email("email@gmail.com") - .name("name") - .password("P@ssw0rd") - .confirmPassword("P@ssw0rd") - .build(); + @MockBean + UserService userService; - userId = userService.save(userDto); + @MockBean + CommentRepository commentRepository; - ArticleDto.Request articleDto = ArticleDto.Request.builder() - .title("title") - .coverUrl("coverUrl") - .contents("contents") - .build(); + private User user = new User(USER_ID, "email@gamil.com", "name", "P@ss0wrd"); + private Article article = new Article("title", "contents", "coverUrl", user); + private Comment comment = new Comment("contents", user, article); + private Comment anotherComment = new Comment("anotherComment", user, article); - articleId = articleService.save(userId, articleDto); + @Test + void 댓글_저장() { + // given + CommentDto.Create commentCreate = mock(CommentDto.Create.class); + when(userService.findById(USER_ID)).thenReturn(user); + when(articleService.findById(any())).thenReturn(article); + when(commentRepository.save(any())).thenReturn(comment); + + // when + final CommentDto.Response commentResponse = commentService.save(commentCreate, USER_ID); + + // then + verify(userService).findById(USER_ID); + verify(articleService).findById(any()); + verify(commentRepository).save(any()); + assertThat(commentResponse.getContents()).isEqualTo(comment.getContents()); + assertThat(commentResponse.getName()).isEqualTo(user.getName()); + } - CommentDto.Create commentDto = new CommentDto.Create(); - commentDto.setArticleId(articleId); - commentDto.setContents("contents"); + @Test + void 댓글_수정() { + // given + CommentDto.Update commentUpdate = mock(CommentDto.Update.class); + when(commentUpdate.toComment()).thenReturn(anotherComment); + when(commentRepository.findById(any())).thenReturn(Optional.ofNullable(comment)); + + // when + final CommentDto.Response commentResponse = commentService.update(commentUpdate, USER_ID); + + // then + verify(commentRepository).findById(any()); + assertThat(commentResponse.getContents()).isEqualTo(anotherComment.getContents()); + assertThat(commentResponse.getName()).isEqualTo(user.getName()); + } - commentId = commentService.save(commentDto, userId).getId(); + @Test + void 다른_작성자_댓글_수정_예외처리() { + // given + CommentDto.Update commentUpdate = mock(CommentDto.Update.class); + when(commentUpdate.toComment()).thenReturn(anotherComment); + when(commentRepository.findById(any())).thenReturn(Optional.ofNullable(comment)); + + // when & then + assertThrows(AuthException.class, () -> commentService.update(commentUpdate, ANOTHER_USER_ID)); } @Test - void update() { - final String modifiedContents = "updateContents"; + void 댓글_삭제() { + // given + when(commentRepository.findById(any())).thenReturn(Optional.ofNullable(comment)); - CommentDto.Update commentDto = new CommentDto.Update(); - commentDto.setId(commentId); - commentDto.setArticleId(articleId); - commentDto.setContents(modifiedContents); + // when + commentService.delete(1L, USER_ID); - final CommentDto.Response modifiedComment = commentService.update(commentDto, userId); + // then + verify(commentRepository).delete(comment); + } + @Test + void 다른_작성자_댓글_삭제_예외처리() { + // given + when(commentRepository.findById(any())).thenReturn(Optional.ofNullable(comment)); - assertThat(modifiedContents).isEqualTo(modifiedComment.getContents()); + // when & then + assertThrows(AuthException.class, () ->commentService.delete(1L, ANOTHER_USER_ID)); } + + // +// @Test +// void update() { +// final String modifiedContents = "updateContents"; +// +// CommentDto.Update commentDto = new CommentDto.Update(); +// commentDto.setId(commentId); +// commentDto.setArticleId(articleId); +// commentDto.setContents(modifiedContents); +// +// final CommentDto.Response modifiedComment = commentService.update(commentDto, userId); +// +// assertThat(modifiedContents).isEqualTo(modifiedComment.getContents()); +// } } \ No newline at end of file From a7c3c42b7763a7c6420cc73f618b1baa13ec7e03 Mon Sep 17 00:00:00 2001 From: DaejunBae Date: Tue, 6 Aug 2019 15:27:13 +0900 Subject: [PATCH 10/29] =?UTF-8?q?feat:=20CommentApi=20CRUD=20=EC=B6=94?= =?UTF-8?q?=EA=B0=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../techcourse/myblog/config/WebConfig.java | 2 +- .../techcourse/myblog/web/api/CommentApi.java | 49 ++++++++++++++--- .../web/controller/CommentController.java | 1 + .../myblog/web/view/CommentResponse.java | 20 ++++--- .../myblog/web/api/CommentApiTest.java | 52 ++++++++++++++++--- 5 files changed, 103 insertions(+), 21 deletions(-) diff --git a/src/main/java/techcourse/myblog/config/WebConfig.java b/src/main/java/techcourse/myblog/config/WebConfig.java index 87a7cb965..45027114a 100644 --- a/src/main/java/techcourse/myblog/config/WebConfig.java +++ b/src/main/java/techcourse/myblog/config/WebConfig.java @@ -29,7 +29,7 @@ public void addInterceptors(InterceptorRegistry registry) { .addPathPatterns("/users") .addPathPatterns("/users/**") .addPathPatterns("/articles/**") - .addPathPatterns("/api/**") +// .addPathPatterns("/api/**") .excludePathPatterns("/users/new") .excludePathPatterns("/users/login"); diff --git a/src/main/java/techcourse/myblog/web/api/CommentApi.java b/src/main/java/techcourse/myblog/web/api/CommentApi.java index fe774d0c2..46b0fd975 100644 --- a/src/main/java/techcourse/myblog/web/api/CommentApi.java +++ b/src/main/java/techcourse/myblog/web/api/CommentApi.java @@ -8,6 +8,7 @@ import techcourse.myblog.dto.CommentDto; import techcourse.myblog.service.CommentService; import techcourse.myblog.web.UserSession; +import techcourse.myblog.web.view.CommentResponse; import java.util.List; @@ -22,16 +23,52 @@ public CommentApi(final CommentService commentService) { this.commentService = commentService; } + @GetMapping + public ResponseEntity> list(@PathVariable Long articleId) { + log.debug("articleId:{}", articleId); + final List comments = commentService.findAllByArticleId(articleId); + + return new ResponseEntity<>(comments, HttpStatus.OK); + } + @PostMapping - public ResponseEntity> create(@PathVariable Long articleId, - @RequestBody CommentDto.Create commentCreate, - UserSession userSession) { + public ResponseEntity create(@PathVariable Long articleId, + @RequestBody CommentDto.Create commentCreate, + UserSession userSession) { log.debug("contents: {}", commentCreate.getContents()); commentCreate.setArticleId(articleId); - commentService.save(commentCreate, userSession.getId()); + final CommentDto.Response savedComment = commentService.save(commentCreate, userSession.getId()); - final List comments = commentService.findAllByArticleId(articleId); - return new ResponseEntity<>(comments, HttpStatus.CREATED); + // TODO 생성 방식 수정 + CommentResponse commentResponse = new CommentResponse(savedComment.getId(), "등록 성공"); + return new ResponseEntity<>(commentResponse, HttpStatus.CREATED); + } + + @DeleteMapping("/{commentId}") + public ResponseEntity delete(@PathVariable Long articleId, + @PathVariable Long commentId, + UserSession userSession) { + log.debug("commentId: {}", commentId); + + commentService.delete(commentId, userSession.getId()); + + CommentResponse commentResponse = new CommentResponse(null, "삭제 성공"); + return new ResponseEntity<>(commentResponse, HttpStatus.OK); + } + + @PutMapping("/{commentId}") + public ResponseEntity update(@PathVariable Long articleId, + @PathVariable Long commentId, + @RequestBody CommentDto.Update commentUpdate, + UserSession userSession) { + log.debug("commentId: {}", commentId); + + commentUpdate.setArticleId(articleId); + commentUpdate.setId(commentId); + commentService.update(commentUpdate, userSession.getId()); + + CommentResponse commentResponse = new CommentResponse(null, "수정 성공"); + return new ResponseEntity<>(commentResponse, HttpStatus.OK); } } diff --git a/src/main/java/techcourse/myblog/web/controller/CommentController.java b/src/main/java/techcourse/myblog/web/controller/CommentController.java index de1734df1..a4712f839 100644 --- a/src/main/java/techcourse/myblog/web/controller/CommentController.java +++ b/src/main/java/techcourse/myblog/web/controller/CommentController.java @@ -9,6 +9,7 @@ import techcourse.myblog.service.CommentService; import techcourse.myblog.web.UserSession; +@Deprecated @Controller @RequestMapping("/articles/{articleId}/comments") @RequiredArgsConstructor diff --git a/src/main/java/techcourse/myblog/web/view/CommentResponse.java b/src/main/java/techcourse/myblog/web/view/CommentResponse.java index e3887a596..93d01cf28 100644 --- a/src/main/java/techcourse/myblog/web/view/CommentResponse.java +++ b/src/main/java/techcourse/myblog/web/view/CommentResponse.java @@ -1,18 +1,26 @@ package techcourse.myblog.web.view; import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; import java.time.LocalDateTime; @Getter +@Setter +@NoArgsConstructor public class CommentResponse { - private final Long id; - private final LocalDateTime time; + private Long id; + private String message; + private String time; - public CommentResponse(final Long id) { - this.id = id; - time = LocalDateTime.now(); + public CommentResponse(final Long id, final String message) { + this(id, message, LocalDateTime.now().toString()); } - + public CommentResponse(final Long id, final String message, String time) { + this.id = id; + this.message = message; + this.time = time; + } } diff --git a/src/test/java/techcourse/myblog/web/api/CommentApiTest.java b/src/test/java/techcourse/myblog/web/api/CommentApiTest.java index a01b4ac7e..0fbffb69a 100644 --- a/src/test/java/techcourse/myblog/web/api/CommentApiTest.java +++ b/src/test/java/techcourse/myblog/web/api/CommentApiTest.java @@ -11,6 +11,7 @@ import reactor.core.publisher.Mono; import techcourse.myblog.dto.CommentDto; import techcourse.myblog.web.controller.BaseControllerTests; +import techcourse.myblog.web.view.CommentResponse; import java.io.IOException; import java.util.List; @@ -27,24 +28,21 @@ class CommentApiTest extends BaseControllerTests { ObjectMapper objectMapper; private String jSessionId; + private Long commentId; @BeforeEach - void setUp() { + void setUp() throws IOException { final String userPassword = "P@ssw0rd"; final String userEmail = "emailArticle@gamil.com"; addUser("name", userEmail, userPassword); jSessionId = getJSessionId(userEmail, userPassword); - } - - @Test - public void create() throws IOException { - final String contents = "changed contents"; + String contents = "changed contents"; CommentDto.Create commentDto = new CommentDto.Create(); commentDto.setContents(contents); - final EntityExchangeResult entityExchangeResult = webTestClient.post().uri("/api/articles/1/comments") + EntityExchangeResult entityExchangeResult = webTestClient.post().uri("/api/articles/1/comments") .contentType(MediaType.APPLICATION_JSON_UTF8) .accept(MediaType.APPLICATION_JSON_UTF8) .cookie(JSESSIONID, jSessionId) @@ -55,9 +53,47 @@ public void create() throws IOException { .expectBody().returnResult(); String body = new String(Objects.requireNonNull(entityExchangeResult.getResponseBody())); + CommentResponse commentResponses = new ObjectMapper().readValue(body, CommentResponse.class); + commentId = commentResponses.getId(); + } - List comments = new ObjectMapper().readValue(body, List.class); + @Test + void list() throws IOException { + EntityExchangeResult entityExchangeResult = webTestClient.get().uri("/api/articles/1/comments") + .accept(MediaType.APPLICATION_JSON_UTF8) + .cookie(JSESSIONID, jSessionId) + .exchange() + .expectStatus().isOk() + .expectHeader().contentType(MediaType.APPLICATION_JSON_UTF8) + .expectBody().returnResult(); + String body = new String(Objects.requireNonNull(entityExchangeResult.getResponseBody())); + List comments = new ObjectMapper().readValue(body, List.class); assertThat(comments).isNotEmpty(); } + + @Test + void delete() throws IOException { + webTestClient.delete().uri("/api/articles/1/comments/{id}", commentId) + .accept(MediaType.APPLICATION_JSON_UTF8) + .cookie(JSESSIONID, jSessionId) + .exchange() + .expectStatus().isOk() + .expectHeader().contentType(MediaType.APPLICATION_JSON_UTF8); + } + + @Test + void update() throws IOException { + String contents = "changed contents"; + CommentDto.Create commentDto = new CommentDto.Create(); + commentDto.setContents(contents); + + webTestClient.put().uri("/api/articles/1/comments/{id}", commentId) + .accept(MediaType.APPLICATION_JSON_UTF8) + .cookie(JSESSIONID, jSessionId) + .body(Mono.just(commentDto), CommentDto.Create.class) + .exchange() + .expectStatus().isOk() + .expectHeader().contentType(MediaType.APPLICATION_JSON_UTF8); + } } \ No newline at end of file From 59415245f63706099b89627d5ff9907a85abf3ad Mon Sep 17 00:00:00 2001 From: DaejunBae Date: Tue, 6 Aug 2019 15:27:36 +0900 Subject: [PATCH 11/29] =?UTF-8?q?feat:=20comments.js=20crud=20ajax=20?= =?UTF-8?q?=EA=B5=AC=ED=98=84?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/main/resources/static/js/comment.js | 141 ++++++++++++++++++++++ src/main/resources/templates/article.html | 76 +++--------- 2 files changed, 155 insertions(+), 62 deletions(-) create mode 100644 src/main/resources/static/js/comment.js diff --git a/src/main/resources/static/js/comment.js b/src/main/resources/static/js/comment.js new file mode 100644 index 000000000..b6b8423e2 --- /dev/null +++ b/src/main/resources/static/js/comment.js @@ -0,0 +1,141 @@ +function editBtnClickHandler(commentId) { + const content = document.getElementById("comment-put-contents-" + commentId); + content.innerHTML = + ` + ` +} + + +const articleId = document.getElementById('articleId').value; +const baseUrl = "/api/articles/" + articleId + "/comments/"; + +const postButton = document.querySelector("#comment-post-button"); +const commentSection = document.getElementById("comment-section") + +postButton.addEventListener("click", postComment); + +// 등록 +function postComment() { + const contents = document.getElementById('comment-post-contents').value; + + fetch(baseUrl, { + method: 'POST', + headers: { + 'Accept': 'application/json; charset=UTF-8', + 'Content-Type': 'application/json; charset=UTF-8', + }, + body: JSON.stringify({ + contents: contents + }), + credentials: "include" + }) + .then(res => res.json()) + .then(json => { + printComments() + }) + .catch(err => console.log(err)) +} + +// 조회 +const printComments = function printComments(e) { + fetch(baseUrl, { + method: 'GET', + headers: { + 'Accept': 'application/json; charset=UTF-8', + 'Content-Type': 'application/json; charset=UTF-8', + }, + }) + .then(res => res.json()) + .then(comments => { + let node = document.getElementById('comment-section'); + while (node.firstChild) { + node.removeChild(node.firstChild); + } + + document.getElementById('comments-size').innerText = comments.length; + + comments.forEach(function (comment) { + console.log(comment) + node.insertAdjacentHTML('beforeend', + template({ + "contents": comment.contents, + "id": comment.id, + "commenter": comment.name, + "modifiedDate": comment.modifiedDate + })) + }) + + }) + .catch(err => console.log(err)) +}; + +const template = (comment) => { + return `
  • + +
    + ${comment.commenter} + +
    + + ${comment.modifiedDate} +
    + + + + +
    +
    + + +

    ${comment.contents}

    +
  • ` +}; + + +commentSection.addEventListener("click", function (event) { + // 수정 + if (event.target.name === 'comment-put') { + const contents = document.getElementById('comment-put-contents').value; + fetch(baseUrl + event.target.dataset.commentId, { + method: 'PUT', + headers: { + 'Accept': 'application/json; charset=UTF-8', + 'Content-Type': 'application/json; charset=UTF-8', + }, + body: JSON.stringify({ + contents: contents + }), + credentials: "include" + }) + .then(res => res.json()) + .then(commentResponse => { + printComments(); + }) + .catch(err => console.log(err)) + } + + //삭제 + if (event.target.name === 'comment-delete') { + fetch(baseUrl + event.target.dataset.commentId, { + method: 'DELETE', + headers: { + 'Accept': 'application/json; charset=UTF-8', + }, + credentials: "include" + }) + .then(res => res.json()) + .then(json => { + printComments() + }) + .catch(err => contents.log(err)) + } + } +); + diff --git a/src/main/resources/templates/article.html b/src/main/resources/templates/article.html index 3b2872c21..1303ac5c3 100644 --- a/src/main/resources/templates/article.html +++ b/src/main/resources/templates/article.html @@ -36,65 +36,33 @@

    댓글 - +
    -
      -
    • - -
      - - - - - - - -
      - -
      -
      - -
      -

      -
      -
      -
    • +
      +
    -
    -
    -
    - - - - -
    - -
    -
    -
    +
    + + +
    +
    + From cff343188c0115b10a6eae4f0bbc07a545557937 Mon Sep 17 00:00:00 2001 From: DaejunBae Date: Tue, 6 Aug 2019 15:27:56 +0900 Subject: [PATCH 12/29] =?UTF-8?q?refactor:=20error.html=20=EC=97=90?= =?UTF-8?q?=EB=9F=AC=EC=B2=98=EB=A6=AC=20=EB=B0=A9=EC=8B=9D=20=EC=88=98?= =?UTF-8?q?=EC=A0=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/main/resources/templates/error.html | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/main/resources/templates/error.html b/src/main/resources/templates/error.html index db1be1d48..e299cce0b 100644 --- a/src/main/resources/templates/error.html +++ b/src/main/resources/templates/error.html @@ -9,8 +9,9 @@