Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[리팩토링] Post, Service 코드 개선 및 테스트 코드 추가 #129

Open
wants to merge 9 commits into
base: develop
Choose a base branch
from
4 changes: 3 additions & 1 deletion build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ dependencies {
// JWT
implementation 'io.jsonwebtoken:jjwt:0.9.1'

// mapstruct
// mapstructㄴ
implementation 'org.mapstruct:mapstruct:1.4.2.Final'

// lombok
Expand Down Expand Up @@ -80,6 +80,8 @@ dependencies {
// test
runtimeOnly 'com.h2database:h2'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
testImplementation 'org.dbunit:dbunit:2.6.0'
testImplementation 'com.github.springtestdbunit:spring-test-dbunit:1.3.0'
}

test {
Expand Down
3 changes: 2 additions & 1 deletion src/main/java/com/yapp18/retrospect/config/ErrorInfo.java
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,8 @@ public enum ErrorInfo {
TEMPLATE_NULL("EE004", "존재하지 않는 템플릿입니다."),
TAG_NULL("EE005", "존재하지 않는 태그입니다."),
IMAGE_NULL("EE006", "존재하지 않는 이미지입니다."),
LIKE_NULL("EE007", "존재하지 않는 스크랩입니다.");
LIKE_NULL("EE007", "존재하지 않는 스크랩입니다."),
CONDITION_NULL("EE008","해당 조건에 맞는 회고글이 없습니다.");

private final String errorCode;
private final String errorMessage;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,7 @@

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
Expand All @@ -16,7 +14,7 @@
import java.util.Locale;

@Configuration
public class JacksonConfiguration {
public class JacksonConfig {

private final Locale locale = Locale.UK;
private final DateTimeFormatter DATE_FORMAT = DateTimeFormatter.ofPattern("MMM dd, yyyy").withLocale(locale);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
import javax.persistence.PersistenceContext;

@Configuration
public class QuerydslConfiguration {
public class QuerydslConfig {

@PersistenceContext
private EntityManager entityManager;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,10 +18,10 @@ public abstract class BaseTimeEntity {

@CreatedDate// Entity가 생성되어 저장될 때 시간이 자동 저장됩니다.
@Column(name ="created_at")
private LocalDateTime createdAt;
protected LocalDateTime createdAt;

@LastModifiedDate// 조회한 Entity의 값을 변경할 때 시간이 자동 저장됩니다.
@Column(name = "modified_at")
private LocalDateTime modifiedAt;
protected LocalDateTime modifiedAt;
}

Original file line number Diff line number Diff line change
Expand Up @@ -3,16 +3,21 @@
import com.yapp18.retrospect.domain.post.Post;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;

public interface CommentRepository extends JpaRepository<Comment, Long> {
List<Comment> findAllByPost(Post post, Pageable page);
@Query(value = "SELECT * FROM comment_tb WHERE comment_tb.post_idx = :postIdx", nativeQuery = true)
List<Comment> findAllByPostIdx(Long postIdx, Pageable page);

// @Query(value = "SELECT COUNT(*) FROM comment_tb WHERE comment_tb.post_idx = :postIdx", nativeQuery = true)
Long countCommentByPost(Post post);

boolean existsByCommentIdxGreaterThanAndPost(Long cursorIdx, Post post);

Long countCommentByPost(Post postIdx);
@Modifying
@Query(value = "ALTER TABLE comment_tb ALTER COLUMN comment_idx RESTART WITH 1", nativeQuery = true)
void restartIdxSequence(); // 테스트 h2 db sequence 초기화용 (postgres에선 사용 불가)
}
2 changes: 1 addition & 1 deletion src/main/java/com/yapp18/retrospect/domain/like/Like.java
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ public class Like extends BaseTimeEntity {

@ManyToOne
@JoinColumn(name = "post_idx")
private Post post; // 어떻게..?
private Post post;

@ManyToOne
@JoinColumn(name = "user_idx")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import com.yapp18.retrospect.domain.user.User;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;

import java.util.List;
Expand All @@ -23,6 +24,8 @@ public interface LikeRepository extends JpaRepository<Like, Long> {
boolean existsByUserAndLikeIdxLessThan(User user, Long lastIdx);

void deleteByUserAndPost(User user, Post post);
// List<Like> findByUserOrderByCreatedAtDesc(Long userIdx, Pageable page);
// Like findByPostAndUser(Post post, User user);

@Modifying
@Query(value = "ALTER TABLE like_tb ALTER COLUMN like_idx RESTART WITH 1", nativeQuery = true)
void restartIdxSequence(); // 테스트 h2 db sequence 초기화용 (postgres에선 사용 불가)
}
4 changes: 1 addition & 3 deletions src/main/java/com/yapp18/retrospect/domain/post/Post.java
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,7 @@

import javax.persistence.*;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;


@Getter @Setter
Expand Down Expand Up @@ -56,7 +54,7 @@ public class Post extends BaseTimeEntity {

@ManyToOne
@JoinColumn(name = "template_idx")
private Template template; // 어떻게?
private Template template;

@JsonIgnore
@OneToMany(mappedBy = "post",orphanRemoval = true)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,15 +5,13 @@
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;

public interface PostRepository extends JpaRepository<Post, Long> {

Post findByPostIdx(Long postIdx);

boolean existsByPostIdxLessThan(Long cursorId);
boolean existsByPostIdx(Long postIdx);

List<Post> findAllByUserUserIdxOrderByCreatedAtDesc(Long userIdx, Pageable pageable);

Expand Down
2 changes: 1 addition & 1 deletion src/main/java/com/yapp18/retrospect/domain/user/Role.java
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
@Getter
@RequiredArgsConstructor
public enum Role {
//스프링 시큐리티에서는 권한 코드에 항상 **ROLE_이 앞에 있어야만 합니다**.
//스프링 시큐리티에서는 권한 코드에 항상 ROLE_이 앞에 있어야만 합니다**.
ADMIN("ROLE_ADMIN", "관리자"),
MEMBER("ROLE_MEMBER", "일반 회원"),
GUEST("ROLE_GUEST", "손님");
Expand Down
11 changes: 5 additions & 6 deletions src/main/java/com/yapp18/retrospect/domain/user/User.java
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,12 @@
import com.sun.istack.NotNull;
import com.yapp18.retrospect.domain.BaseTimeEntity;
import com.yapp18.retrospect.security.oauth2.AuthProvider;

import lombok.*;

import javax.persistence.*;
import java.util.ArrayList;
import java.util.List;

@Getter @Setter
@Entity
@Getter
@Table(name="user_tb")
// 기본 생성자 접근을 protected으로 변경하면 외부에서 해당 생성자를 접근 할 수 없으므로 Builder를 통해서만 객체 생성 가능하므로 안전성 보장
@Builder
Expand Down Expand Up @@ -60,10 +57,10 @@ public User updateNickname(String nickname){
return this;
}

public User updateProfile(String profile, String name, String nickname, String job, String intro){
public User updateProfile(String name, String nickname, String profile, String job, String intro){
this.name = name;
this.profile = profile;
this.nickname = nickname;
this.profile = profile;
this.job = job;
this.intro = intro;
return this;
Expand All @@ -72,4 +69,6 @@ public User updateProfile(String profile, String name, String nickname, String j
public String getRoleKey(){
return this.role.getKey();
}


}
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
package com.yapp18.retrospect.domain.user;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;

import java.util.Optional;

Expand All @@ -9,4 +11,8 @@ public interface UserRepository extends JpaRepository<User, Long> {
Optional<User> findByEmail(String email);
Optional<User> findByUserIdx(Long userIdx);
boolean existsByNickname(String nickname);

@Modifying
@Query(value = "ALTER TABLE user_tb ALTER COLUMN user_idx RESTART WITH 1", nativeQuery = true)
void restartIdxSequence(); // 테스트 h2 db sequence 초기화용 (postgres에선 사용 불가)
}
35 changes: 14 additions & 21 deletions src/main/java/com/yapp18/retrospect/service/CommentService.java
Original file line number Diff line number Diff line change
Expand Up @@ -5,53 +5,46 @@
import com.yapp18.retrospect.domain.comment.Comment;
import com.yapp18.retrospect.domain.comment.CommentRepository;
import com.yapp18.retrospect.domain.post.Post;
import com.yapp18.retrospect.domain.post.PostRepository;
import com.yapp18.retrospect.domain.user.User;
import com.yapp18.retrospect.domain.user.UserRepository;
import com.yapp18.retrospect.mapper.CommentMapper;
import com.yapp18.retrospect.web.advice.EntityNullException;
import com.yapp18.retrospect.web.dto.ApiPagingResultResponse;
import com.yapp18.retrospect.web.dto.CommentDto;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Pageable;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

@RequiredArgsConstructor
@Service
public class CommentService {
private final PostService postService;
private final CommentRepository commentRepository;
private final PostRepository postRepository;

@Transactional
public Comment inputComments(Comment comment){
//타 서비스 의존성을 제거와 코드 가독성을 위해 Entity 외의 메서드 parameter는 최소화 할 것
return commentRepository.save(comment);
Long postIdx = comment.getPost().getPostIdx();
comment.setPost(postService.findByPostIdx(postIdx));
commentRepository.save(comment);
return comment; // commentRepository.save(comment); 그대로 반환하면 테스트 코드에서 엔티티가 null로 날아옴..
}

@Transactional(readOnly = true)
public List<Comment> getCommmentsListByPostIdx(Long postIdx, Pageable page){
Post post = postRepository.findById(postIdx)
.orElseThrow(() -> new EntityNullException(ErrorInfo.POST_NULL));

return commentRepository.findAllByPost(post, page);
public Comment getCommmentsByIdx(Long commentIdx){
return commentRepository.findById(commentIdx)
.orElseThrow(() -> new EntityNullException(ErrorInfo.COMMENT_NULL));
}

@Transactional(readOnly = true)
public Long getCommmentsCountByPostIdx(Long postIdx){
Post post = postRepository.findByPostIdx(postIdx);
return commentRepository.countCommentByPost(post);
public List<Comment> getCommmentsListByPostIdx(Long postIdx, Pageable page){
return commentRepository.findAllByPostIdx(postIdx, page);
}

@Transactional(readOnly = true)
public Comment getCommmentsByIdx(Long commentIdx){
return commentRepository.findById(commentIdx)
.orElseThrow(() -> new EntityNullException(ErrorInfo.COMMENT_NULL));
public Long getCommmentsCountByPostIdx(Long postIdx){
Post post = postService.findByPostIdx(postIdx);
return commentRepository.countCommentByPost(post);
}


Expand All @@ -61,7 +54,7 @@ public Comment updateComments(Comment newComment){
Long commentIdx = newComment.getCommentIdx();

Comment oldComment = commentRepository.findById(commentIdx)
.orElseThrow(() -> new EntityNullException(ErrorInfo.COMMENT_NULL));
.orElseThrow(() -> new EntityNullException(ErrorInfo.COMMENT_NULL));

if(!oldComment.isWriter(newComment.getUser())){
throw new AccessDeniedException(TokenErrorInfo.ACCESS_DENIED.getMessage());
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
package com.yapp18.retrospect.service;

import com.yapp18.retrospect.config.AppProperties;
import com.yapp18.retrospect.domain.user.Role;
import com.yapp18.retrospect.domain.user.User;
import com.yapp18.retrospect.domain.user.UserRepository;
import com.yapp18.retrospect.exception.OAuth2AuthenticationProcessingException;
Expand Down Expand Up @@ -43,7 +41,7 @@ public OAuth2User loadUser(OAuth2UserRequest userRequest) throws OAuth2Authentic
private OAuth2User processOAuth2User(OAuth2UserRequest userRequest, OAuth2User oAuth2User){
String registrationId = userRequest.getClientRegistration().getRegistrationId();

OAuth2UserInfo oAuth2UserInfo = OAuth2UserInfoFactory.getOAuth2UserInfo(registrationId, oAuth2User.getAttributes());;
OAuth2UserInfo oAuth2UserInfo = OAuth2UserInfoFactory.getOAuth2UserInfo(registrationId, oAuth2User.getAttributes());

if(!StringUtils.hasText(oAuth2UserInfo.getEmail())) {
throw new OAuth2AuthenticationProcessingException("OAuth2 공급자(구글, 카카오, ...) 에서 이메일을 찾을 수 없습니다.");
Expand Down
Loading