Skip to content

Commit

Permalink
코드 리팩토링 (#221)
Browse files Browse the repository at this point in the history
* refactor: 불필요한 주석 삭제

* refactor: 필드 초기화를 생성자가 아닌 필드에서 바로 초기화하도록 수정

* refactor: 연관관계 편의 메소드 삭제

* refactor: OneToMany인 경우 Lazy fetch 옵션 제거(default가 Lazy)

* refactor: User Entity 클래스에 AllArgsConstructor 삭제

* test: 테스트 코드 수정
  • Loading branch information
cse0518 authored Jun 13, 2022
1 parent 475de3f commit 614a8ff
Show file tree
Hide file tree
Showing 12 changed files with 84 additions and 192 deletions.
23 changes: 5 additions & 18 deletions src/main/java/org/ahpuh/surf/category/domain/Category.java
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@
import javax.persistence.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@Getter
@NoArgsConstructor(access = AccessLevel.PROTECTED)
Expand All @@ -31,8 +30,8 @@ public class Category extends BaseEntity {
@Column(name = "name", nullable = false)
private String name;

@Column(name = "is_public", nullable = false)
private Boolean isPublic;
@Column(name = "is_public", nullable = false, columnDefinition = "boolean default true")
private Boolean isPublic = true;

@Column(name = "color_code")
private String colorCode;
Expand All @@ -41,32 +40,20 @@ public class Category extends BaseEntity {
@JoinColumn(name = "user_id", referencedColumnName = "user_id")
private User user;

@OneToMany(mappedBy = "category", fetch = FetchType.LAZY, orphanRemoval = true)
private List<Post> posts;

// @Formula("(select count(1) from posts p where p.category_id = category_id and p.is_deleted = false)")
// private int postCount;
@OneToMany(mappedBy = "category", orphanRemoval = true)
private final List<Post> posts = new ArrayList<>();

@Builder
public Category(final User user, final String name, final String colorCode) {
this.user = user;
this.name = name;
this.colorCode = colorCode;
isPublic = true;
posts = new ArrayList<>();
user.addCategory(this);
user.getCategories().add(this);
}

public void update(final String name, final boolean isPublic, final String colorCode) {
this.name = name;
this.isPublic = isPublic;
this.colorCode = colorCode;
}

public void addPost(final Post post) {
if (Objects.isNull(posts)) {
posts = new ArrayList<>();
}
posts.add(post);
}
}
4 changes: 2 additions & 2 deletions src/main/java/org/ahpuh/surf/follow/domain/Follow.java
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ public class Follow {
public Follow(final User source, final User target) {
this.source = source;
this.target = target;
source.addFollowing(this);
target.addFollowers(this);
source.getFollowing().add(this);
target.getFollowers().add(this);
}
}
4 changes: 2 additions & 2 deletions src/main/java/org/ahpuh/surf/like/domain/Like.java
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ public class Like {
public Like(final User user, final Post post) {
this.user = user;
this.post = post;
user.addLike(this);
post.addLike(this);
user.getLikes().add(this);
post.getLikes().add(this);
}
}
22 changes: 6 additions & 16 deletions src/main/java/org/ahpuh/surf/post/domain/Post.java
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@Getter
@NoArgsConstructor(access = AccessLevel.PROTECTED)
Expand Down Expand Up @@ -56,11 +55,11 @@ public class Post extends BaseEntity {
@Column(name = "image_url")
private String imageUrl;

@Column(name = "favorite")
private Boolean favorite;
@Column(name = "favorite", columnDefinition = "boolean default false")
private Boolean favorite = false;

@OneToMany(mappedBy = "post", fetch = FetchType.LAZY, orphanRemoval = true)
private List<Like> likes;
@OneToMany(mappedBy = "post", orphanRemoval = true)
private final List<Like> likes = new ArrayList<>();

@Builder
public Post(final User user, final Category category, final LocalDate selectedDate, final String content, final int score) {
Expand All @@ -69,10 +68,8 @@ public Post(final User user, final Category category, final LocalDate selectedDa
this.selectedDate = selectedDate;
this.content = content;
this.score = score;
favorite = false;
likes = new ArrayList<>();
user.addPost(this);
category.addPost(this);
user.getPosts().add(this);
category.getPosts().add(this);
}

public void updatePost(final Category category, final LocalDate selectedDate, final String content, final int score) {
Expand All @@ -98,11 +95,4 @@ public void updateFavorite(final Long userId) {
}
favorite = !favorite;
}

public void addLike(final Like like) {
if (Objects.isNull(likes)) {
likes = new ArrayList<>();
}
likes.add(like);
}
}
72 changes: 16 additions & 56 deletions src/main/java/org/ahpuh/surf/user/domain/User.java
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
package org.ahpuh.surf.user.domain;

import lombok.*;
import lombok.AccessLevel;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import org.ahpuh.surf.category.domain.Category;
import org.ahpuh.surf.common.domain.BaseEntity;
import org.ahpuh.surf.common.exception.user.InvalidPasswordException;
Expand All @@ -23,7 +26,6 @@

@Getter
@NoArgsConstructor(access = AccessLevel.PROTECTED)
@AllArgsConstructor
@SQLDelete(sql = "UPDATE users SET is_deleted = 1 WHERE user_id = ?")
@Where(clause = "is_deleted = false")
@Entity
Expand Down Expand Up @@ -54,26 +56,26 @@ public class User extends BaseEntity {
private String aboutMe;

@Column(name = "account_public", columnDefinition = "boolean default true")
private Boolean accountPublic;
private Boolean accountPublic = true;

@Column(name = "permission")
@Enumerated(value = EnumType.STRING)
private Permission permission;
private Permission permission = Permission.ROLE_USER;

@OneToMany(mappedBy = "user", fetch = FetchType.LAZY, orphanRemoval = true)
private List<Category> categories;
@OneToMany(mappedBy = "user", orphanRemoval = true)
private final List<Category> categories = new ArrayList<>();

@OneToMany(mappedBy = "user", fetch = FetchType.LAZY, orphanRemoval = true)
private List<Post> posts;
@OneToMany(mappedBy = "user", orphanRemoval = true)
private final List<Post> posts = new ArrayList<>();

@OneToMany(mappedBy = "source", fetch = FetchType.LAZY, orphanRemoval = true)
private List<Follow> following; // 내가 팔로잉한
@OneToMany(mappedBy = "source", orphanRemoval = true)
private final List<Follow> following = new ArrayList<>(); // 내가 팔로잉한

@OneToMany(mappedBy = "target", fetch = FetchType.LAZY, orphanRemoval = true)
private List<Follow> followers; // 나를 팔로우한
@OneToMany(mappedBy = "target", orphanRemoval = true)
private final List<Follow> followers = new ArrayList<>(); // 나를 팔로우한

@OneToMany(mappedBy = "user", fetch = FetchType.LAZY, orphanRemoval = true)
private List<Like> likes;
@OneToMany(mappedBy = "user", orphanRemoval = true)
private final List<Like> likes = new ArrayList<>();

@Formula("(select count(1) from follow f where f.user_id = user_id)")
private int followingCount;
Expand All @@ -86,13 +88,6 @@ public User(final String email, final String password, final String userName) {
this.email = email;
this.password = password;
this.userName = userName;
accountPublic = true;
permission = Permission.ROLE_USER;
categories = new ArrayList<>();
posts = new ArrayList<>();
following = new ArrayList<>();
followers = new ArrayList<>();
likes = new ArrayList<>();
}

public boolean checkPassword(final PasswordEncoder passwordEncoder, final String credentials) {
Expand Down Expand Up @@ -120,39 +115,4 @@ public void update(final PasswordEncoder passwordEncoder, final UserUpdateReques
this.accountPublic = request.getAccountPublic();
profilePhotoUrl.ifPresent(s -> this.profilePhotoUrl = s);
}

public void addCategory(final Category category) {
if (Objects.isNull(categories)) {
categories = new ArrayList<>();
}
categories.add(category);
}

public void addPost(final Post post) {
if (Objects.isNull(posts)) {
posts = new ArrayList<>();
}
posts.add(post);
}

public void addFollowing(final Follow followingUser) {
if (Objects.isNull(following)) {
following = new ArrayList<>();
}
following.add(followingUser);
}

public void addFollowers(final Follow follower) {
if (Objects.isNull(followers)) {
followers = new ArrayList<>();
}
followers.add(follower);
}

public void addLike(final Like like) {
if (Objects.isNull(likes)) {
likes = new ArrayList<>();
}
likes.add(like);
}
}
43 changes: 0 additions & 43 deletions src/test/java/org/ahpuh/surf/common/factory/MockUserFactory.java
Original file line number Diff line number Diff line change
@@ -1,15 +1,12 @@
package org.ahpuh.surf.common.factory;

import org.ahpuh.surf.user.domain.Permission;
import org.ahpuh.surf.user.domain.User;
import org.ahpuh.surf.user.dto.request.UserJoinRequestDto;
import org.ahpuh.surf.user.dto.request.UserLoginRequestDto;
import org.ahpuh.surf.user.dto.request.UserUpdateRequestDto;
import org.ahpuh.surf.user.dto.response.UserFindInfoResponseDto;
import org.ahpuh.surf.user.dto.response.UserLoginResponseDto;

import java.util.ArrayList;

public class MockUserFactory {

public static User createMockUser() {
Expand All @@ -36,46 +33,6 @@ public static User createMockUser(final String email, final String password, fin
.build();
}

public static User createSavedUser() {
return new User(1L,
"mock",
"[email protected]",
"$2a$10$1dmE40BM1RD2lUg.9ss24eGs.4.iNYq1PwXzqKBfIXNRbKCKliqbG",
null,
null,
null,
true,
Permission.ROLE_USER,
new ArrayList<>(),
new ArrayList<>(),
new ArrayList<>(),
new ArrayList<>(),
new ArrayList<>(),
0,
0
);
}

public static User createSavedUserWithProfileImage() {
return new User(1L,
"mock",
"[email protected]",
"$2a$10$1dmE40BM1RD2lUg.9ss24eGs.4.iNYq1PwXzqKBfIXNRbKCKliqbG",
"profilePhoto",
null,
null,
true,
Permission.ROLE_USER,
new ArrayList<>(),
new ArrayList<>(),
new ArrayList<>(),
new ArrayList<>(),
new ArrayList<>(),
0,
0
);
}

public static UserJoinRequestDto createUserJoinRequestDto() {
return UserJoinRequestDto.builder()
.email("[email protected]")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -153,7 +153,9 @@ class UpdateTest {
@Test
void updateUserWithProfileImageSuccess() {
// Given
final User user = userRepository.save(createSavedUser());
final User user = userRepository.save(createMockUser("[email protected]",
"$2a$10$1dmE40BM1RD2lUg.9ss24eGs.4.iNYq1PwXzqKBfIXNRbKCKliqbG",
"mock"));
assertAll("유저 정보 변경전",
() -> assertThat(user.getUserName()).isEqualTo("mock"),
() -> assertThat(passwordEncoder.matches("testpw", user.getPassword())).isTrue(),
Expand Down Expand Up @@ -184,7 +186,9 @@ void updateUserWithProfileImageSuccess() {
@Test
void updateUserWithNoProfileImageSuccess() {
// Given
final User user = userRepository.save(createSavedUser());
final User user = userRepository.save(createMockUser("[email protected]",
"$2a$10$1dmE40BM1RD2lUg.9ss24eGs.4.iNYq1PwXzqKBfIXNRbKCKliqbG",
"mock"));
assertAll("유저 정보 변경전",
() -> assertThat(user.getUserName()).isEqualTo("mock"),
() -> assertThat(passwordEncoder.matches("testpw", user.getPassword())).isTrue(),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
import org.junit.jupiter.api.Test;

import static org.ahpuh.surf.common.factory.MockCategoryFactory.createMockCategory;
import static org.ahpuh.surf.common.factory.MockUserFactory.createSavedUser;
import static org.ahpuh.surf.common.factory.MockUserFactory.createMockUser;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.assertAll;

Expand All @@ -16,7 +16,7 @@ public class CategoryTest {
@Test
void updateCategoryTest() {
// Given
final User user = createSavedUser();
final User user = createMockUser();
final Category category = createMockCategory(user);

// When
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import org.ahpuh.surf.jwt.JwtAuthentication;
import org.ahpuh.surf.jwt.JwtAuthenticationProvider;
import org.ahpuh.surf.jwt.JwtAuthenticationToken;
import org.ahpuh.surf.user.domain.Permission;
import org.ahpuh.surf.user.domain.User;
import org.ahpuh.surf.user.service.UserService;
import org.junit.jupiter.api.DisplayName;
Expand All @@ -14,11 +15,11 @@
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.security.core.Authentication;

import static org.ahpuh.surf.common.factory.MockUserFactory.createSavedUser;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.assertAll;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;

@ExtendWith(MockitoExtension.class)
public class JwtAuthenticationProviderTest {
Expand All @@ -36,11 +37,17 @@ public class JwtAuthenticationProviderTest {
@Test
void authenticateTest() {
// Given
final User user = createSavedUser();
final User user = mock(User.class);
given(userService.login("cse0518", "password"))
.willReturn(user);
given(jwt.sign(any()))
.willReturn("token");
given(user.getPermission())
.willReturn(Permission.ROLE_USER);
given(user.getUserId())
.willReturn(1L);
given(user.getEmail())
.willReturn("[email protected]");

// When
final Authentication authentication
Expand Down
Loading

0 comments on commit 614a8ff

Please sign in to comment.