Skip to content

Commit

Permalink
Merge pull request #74 from dnd-side-project/fix/#73-formatter
Browse files Browse the repository at this point in the history
코드 포맷터를 수정한다.
  • Loading branch information
f1v3-dev authored Feb 5, 2025
2 parents 169d770 + fd19507 commit 1144db9
Show file tree
Hide file tree
Showing 19 changed files with 61 additions and 104 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -66,9 +66,6 @@ public ApiResponse<FindBookDetailsResponse> findBookDetails(@PathVariable Long m
* @return 회원 ID (null: guest)
*/
private Long extractMemberId(UserDetails user) {
return Optional.ofNullable(user)
.map(UserDetails::getUsername)
.map(Long::valueOf)
.orElse(null);
return Optional.ofNullable(user).map(UserDetails::getUsername).map(Long::valueOf).orElse(null);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -34,8 +34,7 @@ public FindAllBookResponse findAllMemberBooks(
validateBookAccess(member, targetMemberId, currentMemberId);

return FindAllBookResponse.of(
memberBookRepository.findMemberBookByMemberIdAndReadStatus(
targetMemberId, readStatus));
memberBookRepository.findMemberBookByMemberIdAndReadStatus(targetMemberId, readStatus));
}

@Transactional(readOnly = true)
Expand All @@ -53,8 +52,7 @@ public FindBookDetailsResponse findBookDetails(Long memberBookId) {
return FindBookDetailsResponse.of(memberBookRepository.findBookDetails(memberBookId));
}

private void validateBookAccess(
MemberEntity member, Long targetMemberId, Long currentMemberId) {
private void validateBookAccess(MemberEntity member, Long targetMemberId, Long currentMemberId) {
if (!member.isBookPublic() && !targetMemberId.equals(currentMemberId)) {
throw new BookForbiddenException(ErrorType.BOOK_ACCESS_FORBIDDEN);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,13 +18,13 @@
@RequestMapping("/api")
public class RegisterBookController implements RegisterBookApiSpec {

private final RegisterBookUsecase registerBookUsecase;
private final RegisterBookUseCase registerBookUseCase;

@PostMapping("/books")
public ApiResponse<?> registerBook(
@Valid @RequestBody RegisterBookRequest request,
@Parameter(hidden = true) @AuthenticationPrincipal UserDetails userDetails) {
registerBookUsecase.registerBook(request, Long.valueOf(userDetails.getUsername()));
registerBookUseCase.registerBook(request, Long.valueOf(userDetails.getUsername()));
return ApiResponse.success();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
@Service
@RequiredArgsConstructor
@Transactional
public class RegisterBookUsecase {
public class RegisterBookUseCase {
private final MemberBookRepository memberBookRepository;
private final BookRepository bookRepository;
private final MemberRepository memberRepository;
Expand All @@ -23,8 +23,7 @@ public void registerBook(RegisterBookRequest request, Long memberId) {
.orElseThrow(() -> new RuntimeException()); // todo 커스텀한 예외로 수정
BookEntity bookEntity =
bookRepository.save(
BookEntity.newInstance(
request.author(), request.title(), request.publishedAt()));
BookEntity.newInstance(request.author(), request.title(), request.publishedAt()));
memberBookRepository.save(
MemberBookEntity.newInstance(
memberEntity, bookEntity, ReadStatus.valueOf(request.readStatus())));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,14 +18,14 @@ public boolean isValid(String value, ConstraintValidatorContext context) {
Object[] enumValues = this.annotation.enumClass().getEnumConstants();
if (enumValues != null) {
for (Object enumValue : enumValues) {
if (value.equals(enumValue.toString())
|| (value.equalsIgnoreCase(enumValue.toString()))) {
if (value.equals(enumValue.toString()) || (value.equalsIgnoreCase(enumValue.toString()))) {
result = true;
break;
}
}
}
context.buildConstraintViolationWithTemplate(value + ValidationMessage.ENUM_SUFFIX)
context
.buildConstraintViolationWithTemplate(value + ValidationMessage.ENUM_SUFFIX)
.addConstraintViolation()
.disableDefaultConstraintViolation();
return result;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,5 @@
public interface UpdateBookApiSpec {

@Operation(summary = "책 수정", description = "회원이 등록한 책을 수정한다.")
ApiResponse<?> updateBook(
UserDetails userDetails, Long memberBookId, UpdateBookRequest request);
ApiResponse<?> updateBook(UserDetails userDetails, Long memberBookId, UpdateBookRequest request);
}
Original file line number Diff line number Diff line change
Expand Up @@ -23,9 +23,7 @@ public FindEquippedItemsResponse findEquippedItems(Long memberId) {
.collect(
Collectors.groupingBy(
findItemDTO -> findItemDTO.type(),
Collectors.mapping(
findItemDTO -> findItemDTO.code(),
Collectors.toList())));
Collectors.mapping(findItemDTO -> findItemDTO.code(), Collectors.toList())));
return FindEquippedItemsResponse.from(equippedItems);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -29,8 +29,7 @@ public ApiResponse<FindItemsResponse> findMyItems(
@GetMapping("/items/equipped")
public ApiResponse<FindEquippedItemsResponse> findEquippedItems(
@Parameter(hidden = true) @AuthenticationPrincipal UserDetails user) {
return ApiResponse.success(
findEquippedItemUsecase.findEquippedItems(extractMemberId(user)));
return ApiResponse.success(findEquippedItemUsecase.findEquippedItems(extractMemberId(user)));
}

private Long extractMemberId(UserDetails user) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,9 +26,7 @@ public FindItemsResponse findMyItems(Long memberId) {
findItemDTO -> findItemDTO.type(),
Collectors.mapping(
findItemDTO ->
FindItemResponse.from(
findItemDTO.name(),
findItemDTO.code()),
FindItemResponse.from(findItemDTO.name(), findItemDTO.code()),
Collectors.toList())));
return FindItemsResponse.from(items);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,8 +37,7 @@ public class AuthController implements AuthApiSpec {
*/
@PostMapping("/auth/reissue")
public ApiResponse<?> reissue(
@CookieValue(value = "refreshToken") String refreshToken,
HttpServletResponse response) {
@CookieValue(value = "refreshToken") String refreshToken, HttpServletResponse response) {
tokenUsecase.validateRefreshToken(refreshToken);
setToken(response, refreshToken);
return ApiResponse.success();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -60,22 +60,16 @@ public OAuth2User loadUser(OAuth2UserRequest userRequest) throws OAuth2Authentic
*/
private MemberEntity getOrSave(OAuth2UserDTO oAuth2UserDTO) {
return memberRepository
.findByKakaoIdAndRegistrationId(
oAuth2UserDTO.kakaoId(), oAuth2UserDTO.registrationId())
.findByKakaoIdAndRegistrationId(oAuth2UserDTO.kakaoId(), oAuth2UserDTO.registrationId())
.orElseGet(
() -> {
MemberEntity savedMember =
memberRepository.save(oAuth2UserDTO.toEntity());
MemberEntity savedMember = memberRepository.save(oAuth2UserDTO.toEntity());
likeRepository.save(LikeEntity.newInstance(savedMember.getId()));
ItemEntity itemEntity =
itemRepository
.findById(1L)
.orElseThrow(
() ->
new ItemNotFoundException(
ITEM_NOT_FOUND));
memberItemRepository.save(
MemberItemEntity.newInstance(savedMember, itemEntity));
.orElseThrow(() -> new ItemNotFoundException(ITEM_NOT_FOUND));
memberItemRepository.save(MemberItemEntity.newInstance(savedMember, itemEntity));
return savedMember;
});
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -60,23 +60,22 @@ public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Excepti
.sessionManagement(c -> c.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.authorizeHttpRequests(
request ->
request.requestMatchers(allowUrls)
request
.requestMatchers(allowUrls)
.permitAll()
.requestMatchers(HttpMethod.GET, openGetApiUrls)
.permitAll()
.anyRequest()
.authenticated())
.oauth2Login(
oauth ->
oauth.authorizationEndpoint(
endPoint -> endPoint.baseUri("/api/login"))
oauth
.authorizationEndpoint(endPoint -> endPoint.baseUri("/api/login"))
.userInfoEndpoint(c -> c.userService(oAuth2UserService))
.successHandler(oAuth2SuccessHandler))
.addFilterBefore(tokenAuthenticationFilter, UsernamePasswordAuthenticationFilter.class)
.addFilterBefore(
tokenAuthenticationFilter, UsernamePasswordAuthenticationFilter.class)
.addFilterBefore(
new TokenExceptionFilter(objectMapper),
tokenAuthenticationFilter.getClass());
new TokenExceptionFilter(objectMapper), tokenAuthenticationFilter.getClass());

return http.build();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,8 +30,7 @@ protected void doFilterInternal(
}
}

private void handleApiException(HttpServletResponse response, ApiException e)
throws IOException {
private void handleApiException(HttpServletResponse response, ApiException e) throws IOException {
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
response.setContentType(MediaType.APPLICATION_JSON_VALUE);
response.setCharacterEncoding("UTF-8");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -50,11 +50,7 @@ public boolean validateToken(String token) {

private Claims parseClaims(String token) {
try {
return Jwts.parser()
.verifyWith(secretKey)
.build()
.parseSignedClaims(token)
.getPayload();
return Jwts.parser().verifyWith(secretKey).build().parseSignedClaims(token).getPayload();
} catch (ExpiredJwtException e) {
throw new ExpiredTokenException(ErrorType.EXPIRED_TOKEN);
} catch (MalformedJwtException e) {
Expand Down Expand Up @@ -98,7 +94,6 @@ public Authentication getAuthentication(String token) {
}

private List<SimpleGrantedAuthority> getAuthorities(Claims claims) {
return Collections.singletonList(
new SimpleGrantedAuthority(claims.get(KEY_ROLE).toString()));
return Collections.singletonList(new SimpleGrantedAuthority(claims.get(KEY_ROLE).toString()));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -26,8 +26,7 @@ public void validateRefreshToken(String refreshToken) {
private boolean isMatched(String refreshToken) {
return redisRepository
.getData(
RedisKey.getRefreshTokenKey(
tokenProvider.getAuthentication(refreshToken).getName()))
RedisKey.getRefreshTokenKey(tokenProvider.getAuthentication(refreshToken).getName()))
.equals(refreshToken);
}
}
52 changes: 18 additions & 34 deletions api/src/main/java/com/dnd/sbooky/api/support/error/ErrorType.java
Original file line number Diff line number Diff line change
@@ -1,51 +1,35 @@
package com.dnd.sbooky.api.support.error;

import static org.springframework.http.HttpStatus.*;

import lombok.Getter;
import org.springframework.boot.logging.LogLevel;
import org.springframework.http.HttpStatus;

@Getter
public enum ErrorType {

// TODO: 에러 타입 정의 필요
DEFAULT_ERROR(
HttpStatus.INTERNAL_SERVER_ERROR,
ErrorCode.E500,
"An unexpected error has occurred.",
LogLevel.ERROR),

NOT_FOUND(
HttpStatus.NOT_FOUND,
ErrorCode.E404,
"The requested resource was not found.",
LogLevel.INFO),

INVALID_TOKEN(
HttpStatus.UNAUTHORIZED, ErrorCode.SECURITY_401_1, "Invalid token.", LogLevel.INFO),

INVALID_SIGNATURE(
HttpStatus.UNAUTHORIZED, ErrorCode.SECURITY_401_2, "Invalid signature", LogLevel.INFO),

EXPIRED_TOKEN(
HttpStatus.UNAUTHORIZED,
ErrorCode.SECURITY_401_3,
"Expired accessToken",
LogLevel.INFO),
// TODO: 에러 타입 정의

NOT_FOUND_TOKEN(
HttpStatus.NOT_FOUND, ErrorCode.SECURITY_404_1, "Not found token", LogLevel.INFO),
// Server Error
DEFAULT_ERROR(INTERNAL_SERVER_ERROR, ErrorCode.E500, "Internal server error.", LogLevel.ERROR),
INVALID_PARAMETER(BAD_REQUEST, ErrorCode.E400, "Request parameter is invalid.", LogLevel.INFO),

INVALID_PARAMETER(
HttpStatus.BAD_REQUEST, ErrorCode.E400, "Request parameter is invalid.", LogLevel.INFO),
// Security Error
INVALID_TOKEN(UNAUTHORIZED, ErrorCode.SECURITY_401_1, "Invalid token.", LogLevel.INFO),
INVALID_SIGNATURE(UNAUTHORIZED, ErrorCode.SECURITY_401_2, "Invalid signature", LogLevel.INFO),
EXPIRED_TOKEN(UNAUTHORIZED, ErrorCode.SECURITY_401_3, "Expired accessToken", LogLevel.INFO),
NOT_FOUND_TOKEN(NOT_FOUND, ErrorCode.SECURITY_404_1, "Not found token", LogLevel.INFO),

MEMBER_NOT_FOUND(
HttpStatus.NOT_FOUND, ErrorCode.MEMBER_404, "Member not found.", LogLevel.INFO),
// Member Error
MEMBER_NOT_FOUND(NOT_FOUND, ErrorCode.MEMBER_404, "Member not found.", LogLevel.INFO),

BOOK_ACCESS_FORBIDDEN(
HttpStatus.FORBIDDEN, ErrorCode.BOOK_403, "Book access is forbidden.", LogLevel.INFO),
// Book Error
BOOK_ACCESS_FORBIDDEN(FORBIDDEN, ErrorCode.BOOK_403, "Book access is forbidden.", LogLevel.INFO),
BOOK_NOT_FOUND(NOT_FOUND, ErrorCode.BOOK_404, "Book was not found.", LogLevel.INFO),

BOOK_NOT_FOUND(HttpStatus.NOT_FOUND, ErrorCode.BOOK_404, "Book was not found.", LogLevel.INFO),
ITEM_NOT_FOUND(HttpStatus.NOT_FOUND, ErrorCode.ITEM_404, "Item was not found.", LogLevel.INFO);
// Item Error
ITEM_NOT_FOUND(NOT_FOUND, ErrorCode.ITEM_404, "Item was not found.", LogLevel.INFO);

private final HttpStatus status;
private final ErrorCode code;
Expand Down
19 changes: 12 additions & 7 deletions build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -51,14 +51,19 @@ subprojects {

spotless {
java {
importOrder()
// Google Java Format을 기본 포매터로 사용
googleJavaFormat()
.reflowLongStrings() // 긴 문자열을 여러 줄로 나누어 포맷팅
.formatJavadoc(false) // Javadoc 포맷팅 비활성화
.reorderImports(false) // import문 재정렬 비활성화
.groupArtifact('com.google.googlejavaformat:google-java-format') // 사용할 구글 포맷터 버전 지정

removeUnusedImports()
cleanthat()

googleJavaFormat().aosp().reflowLongStrings().formatJavadoc(false).reorderImports(false).groupArtifact('com.google.googlejavaformat:google-java-format')

formatAnnotations() // fixes formatting of type annotations, see below
indentWithTabs(2) // 탭을 사용한 들여쓰기 설정 (탭 크기 2)
indentWithSpaces(4) // 공백을 사용한 들여쓰기 설정 (공백 4칸)
importOrder() // import문 순서 설정 (기본값 사용)
removeUnusedImports() // 사용하지 않는 import문 제거
cleanthat() // 코드 리팩토링 도구 적용
formatAnnotations() // 어노테이션 포맷팅 적용
}
}
}
Expand Down
3 changes: 1 addition & 2 deletions core/src/main/java/com/dnd/sbooky/core/Initializer.java
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,7 @@ public class Initializer {

@PostConstruct
public void init() {
MemberEntity memberEntity =
memberRepository.save(MemberEntity.newInstance("test1", "test1"));
MemberEntity memberEntity = memberRepository.save(MemberEntity.newInstance("test1", "test1"));
likeRepository.save(LikeEntity.newInstance(memberEntity.getId()));
itemRepository.save(ItemEntity.newInstance(ItemType.CHARACTER, "떠돌이 유령", "mummy_ghost"));
itemRepository.save(ItemEntity.newInstance(ItemType.CHARACTER, "유령", "basic_ghost"));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -49,11 +49,7 @@ public class MemberEntity extends BaseEntity {

@Builder
private MemberEntity(
String nickname,
String introduction,
String kakaoId,
String registrationId,
Role role) {
String nickname, String introduction, String kakaoId, String registrationId, Role role) {
this.kakaoId = kakaoId;
this.registrationId = registrationId;
this.nickname = nickname;
Expand Down

0 comments on commit 1144db9

Please sign in to comment.