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

[BE] user 에러 & 페이지 에러 수정 #191

Merged
merged 4 commits into from
Dec 7, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions backend/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -69,4 +69,5 @@ tasks.named('test') {

tasks.withType(JavaCompile) {
options.annotationProcessorPath = configurations.annotationProcessor
options.compilerArgs << "-parameters"
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,15 @@

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import java.util.List;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.example.backend.board.domain.dto.BoardReqDto;
import org.example.backend.board.domain.dto.BoardResDto;
import org.example.backend.board.domain.entity.Category;
import org.example.backend.board.service.BoardService;
import org.example.backend.common.dto.PageRequestDto;
import org.example.backend.common.dto.ResponseDto;
import org.springframework.data.domain.Page;
import org.springframework.http.HttpStatus;
Expand Down Expand Up @@ -41,23 +43,17 @@ public ResponseEntity<Long> createBoard(@RequestPart(value = "boardReqDto") Boar

@Operation(summary = "모든 게시판 조회 API", description = "모든 게시판의 리스트 반환")
@GetMapping
public ResponseDto<List<BoardResDto>> getAllBoards(@RequestParam(defaultValue = "0") int page,
@RequestParam(defaultValue = "10") int size,
@RequestParam(defaultValue = "id") String sort,
@RequestParam(defaultValue = "ASC") String sortDirection) {
public ResponseDto<List<BoardResDto>> getAllBoards(@Valid PageRequestDto pageRequest) {

Page<BoardResDto> boardList = boardService.getAllBoards(page, size, sort, sortDirection);
Page<BoardResDto> boardList = boardService.getAllBoards(pageRequest.toPageable());
return ResponseDto.ok(boardList.getNumber(), boardList.getTotalPages(), boardList.getContent());
}
@Operation(summary = "카테고리별 게시판 조회 API", description = "카테고리별 게시판 리스트 반환")
@GetMapping("/category/{category}")
public ResponseDto<List<BoardResDto>> getBoardsByCategory(@PathVariable("category") Category category,
@RequestParam(defaultValue = "0") int page,
@RequestParam(defaultValue = "10") int size,
@RequestParam(defaultValue = "id") String sort,
@RequestParam(defaultValue = "ASC") String sortDirection) {
@Valid PageRequestDto pageRequest) {

Page<BoardResDto> boardList = boardService.getBoardsByCategory(category, page, size, sort, sortDirection);
Page<BoardResDto> boardList = boardService.getBoardsByCategory(category, pageRequest.toPageable());
return ResponseDto.ok(boardList.getNumber(), boardList.getTotalPages(), boardList.getContent());
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
import lombok.RequiredArgsConstructor;
import org.example.backend.common.exception.BaseException;
import org.example.backend.common.exception.BaseExceptionType;
import org.example.backend.board.exception.BoardExceptionType;

@RequiredArgsConstructor
public class BoardException extends BaseException {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -54,16 +54,12 @@ public BoardResDto getBoard(Long boardId) {
return BoardResDto.of(board);
}

public Page<BoardResDto> getAllBoards(int pageNo, int pageSize, String sortBy, String sortDirection) {
Sort sort = Sort.by(Sort.Direction.fromString(sortDirection), sortBy);
Pageable pageable = PageRequest.of(pageNo, pageSize, sort);
public Page<BoardResDto> getAllBoards(Pageable pageable) {
return boardRepository.findAll(pageable)
.map(BoardResDto::of);
}

public Page<BoardResDto> getBoardsByCategory(Category category, int pageNo, int pageSize, String sortBy, String sortDirection) {
Sort sort = Sort.by(Sort.Direction.fromString(sortDirection), sortBy);
Pageable pageable = PageRequest.of(pageNo, pageSize, sort);
public Page<BoardResDto> getBoardsByCategory(Category category, Pageable pageable) {
return boardRepository.findAllByCategory(category, pageable)
.map(BoardResDto::of);
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
package org.example.backend.common.dto;

import jakarta.validation.constraints.Max;
import jakarta.validation.constraints.Min;
import lombok.Getter;
import lombok.Setter;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;

@Getter
@Setter
public class PageRequestDto {
@Min(0)
private int page = 0;

@Min(1) @Max(100)
private int size = 10;

private String sort = "id";
private String sortDirection = "ASC";

public Pageable toPageable() {
Sort.Direction direction = Sort.Direction.valueOf(sortDirection.toUpperCase());
return PageRequest.of(page, size, direction, sort);
}
}
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
package org.example.backend.common.exception;

import static java.util.stream.Collectors.joining;
import static org.springframework.http.HttpStatus.BAD_REQUEST;

import jakarta.servlet.http.HttpServletRequest;
Expand All @@ -10,6 +9,7 @@
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
Expand Down Expand Up @@ -69,4 +69,12 @@ > handleInvalidPaginationParameterException(InvalidPaginationParameterException
return ResponseEntity.status(BAD_REQUEST)
.body(new ExceptionResponse(e.getExceptionType().errorMessage()));
}

@ExceptionHandler({MethodArgumentNotValidException.class})
public ResponseEntity<ExceptionResponse> validException(
MethodArgumentNotValidException e) {

return ResponseEntity.status(BAD_REQUEST)
.body(new ExceptionResponse(e.getMessage()));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,15 @@

import lombok.Getter;
import lombok.RequiredArgsConstructor;
import org.example.backend.common.exception.BaseException;

@Getter
@RequiredArgsConstructor
public class InvalidPaginationParameterException extends RuntimeException {
public class InvalidPaginationParameterException extends BaseException {
private final InvalidPaginationParameterExceptionType exceptionType;
}

@Override
public InvalidPaginationParameterExceptionType exceptionType(){
return exceptionType;
}
}
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
package org.example.backend.common.exception.paging;

import lombok.RequiredArgsConstructor;
import org.example.backend.common.exception.BaseExceptionType;
import org.springframework.http.HttpStatus;

@RequiredArgsConstructor
public enum InvalidPaginationParameterExceptionType implements BaseExceptionType {
INVALID_PAGE("페이지 번호는 0 이상이어야 합니다.", HttpStatus.BAD_REQUEST),
INVALID_SIZE("페이지 크기는 양의 정수여야 합니다.", HttpStatus.BAD_REQUEST),
Expand All @@ -11,10 +13,6 @@ public enum InvalidPaginationParameterExceptionType implements BaseExceptionType
private final String message;
private final HttpStatus httpStatus;

InvalidPaginationParameterExceptionType(String message, HttpStatus httpStatus) {
this.message = message;
this.httpStatus = httpStatus;
}

@Override
public String errorMessage() {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
package org.example.backend.user.repository;

import java.util.Optional;
import org.example.backend.user.domain.entity.User;
import org.springframework.data.jpa.repository.JpaRepository;

public interface UserRepository extends JpaRepository<User, Long> {
Optional<User> findByStudentId(String studentId);
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import static org.example.backend.user.exception.UserExceptionType.NOT_FOUND_USER;

import java.util.Optional;
import org.example.backend.user.domain.entity.User;
import org.springframework.data.domain.Pageable;
import lombok.RequiredArgsConstructor;
Expand Down Expand Up @@ -37,7 +38,15 @@ public String loginProcess(SignInReqDto joinDTO) {
.studentId(sjProfile.getStudentCode())
.major(sjProfile.getMajor())
.build();
Long userId = saveUser(userReqDto);

Long userId;
Optional<User> optionalUser = findUser(userReqDto);
if(optionalUser.isEmpty()){
userId = saveUser(userReqDto);
}else {
userId = Long.valueOf(optionalUser.get().getStudentId());
}


return jwtUtil.createJwt(String.valueOf(userId), "USER", 60 * 60 * 10L);
} catch (RuntimeException e) {
Expand All @@ -53,6 +62,11 @@ public Long saveUser(UserReqDto userReqDto) {
return savedUser.getId();
}

private Optional<User> findUser(UserReqDto userReqDto){
validateRequiredFields(userReqDto);
return userRepository.findByStudentId(userReqDto.getStudentId());
}

private void validateRequiredFields(UserReqDto userReqDto) {
if (userReqDto.getName() == null || userReqDto.getName().isEmpty()) {
throw new UserException(UserExceptionType.REQUIRED_NAME);
Expand Down Expand Up @@ -88,6 +102,4 @@ private User findUserById(Long userId) {
return userRepository.findById(userId)
.orElseThrow(() -> new UserException(NOT_FOUND_USER));
}


}
Loading
Loading