[ 작업한 내용 ]
< 사용자(본인) 도서 대출 내역 조회 >
1. UserLoanListResDTO
- 사용자(본인) 도서 대출 내역 전체 조회시 응답 DTO.
- id, bookTitle, author, publisher, publishedDate, loanDate, returnDate 필드.
- Loan 엔티티를 파라미터로 받는 UserLoanListResDTO 생성자 함수 정의.
@Getter
public class UserLoanListResDTO {
private Long id;
private String bookTitle;
private String author;
private String publisher;
private LocalDate publishedDate;
private LocalDateTime loanDate;
private LocalDateTime returnDate;
public UserLoanListResDTO(Loan loan) {
this.id = loan.getId();
this.bookTitle = loan.getBook().getTitle();
this.author = loan.getBook().getAuthor();
this.publisher = loan.getBook().getPublisher();
this.publishedDate = loan.getBook().getPublishedDate();
this.loanDate = loan.getLoanDate();
this.returnDate = loan.getReturnDate();
}
}
2. UserLoanController
- GET /api/v1/user/me/loans 요청을 처리한다.
- 요청받는 파라미터는 page, size이며, 각각 기본 0과 10으로 설정되어 있다.
- AuthenticationPrincipal User user를 통해 현재 인증된 사용자 정보를 받는다.
- Service 계층으로 page, size, user를 전달해 대출 목록을 조회한다.
- 결과는 Page<UserLoanListResDTO>형태이다.
- 클라이언트 측으로 성공메시지와 결과를 ApiResponse.success()로 감싸서 반환한다.
@GetMapping("/loans")
public ResponseEntity<?> userLoanList(
@RequestParam(name = "page", defaultValue = "0") int page,
@RequestParam(name = "size", defaultValue = "10") int size,
@AuthenticationPrincipal User user
) {
// 서비스로직
Page<UserLoanListResDTO> responseDTO = userLoanService.userLoanList(page, size, user);
// 성공메시지
String message = messageProvider.getMessage(LoanSuccessCode.LOAN_LIST_FETCHED.getMessage());
// 반환
return ResponseEntity
.status(LoanSuccessCode.LOAN_LIST_FETCHED.getHttpStatus())
.body(ApiResponse.success(
LoanSuccessCode.LOAN_LIST_FETCHED,
message,
responseDTO));
}
3. UserLoanService
- page, size, user를 파라미터로 받고, Page<UserLoanListResDTO> 형태로 반환한다.
- user.getId()를 통해 사용자 ID를 가져오고, userRepository.findById()로 실제 사용자 유무를 검증한다. 사용자가 없다면 UserErrorCode.USER_NOT_FOUND 예외를 던진다.
- 유효한 사용자인 경우, 조회된 엔티티를 userFromDb에 저장한다.
- PageRequest.of(page, size)로 Pageable 생성
- loanRepository.findByUserId(userId, pageable)을 통해 해당 사용자의 대출 정보를 페이징 처리하여 조회한다.
- 조회된 결과는 DTO 리스트로 변환한 후, PageImpl<>로 감싸서 컨트롤러에 반환한다.
// 사용자(본인) 도서 대출 내역 조회 (페이징)
public Page<UserLoanListResDTO> userLoanList(int page, int size, User user) {
// 사용자 조회(유효 검사)
User userFromDb = userRepository.findById(user.getId())
.orElseThrow(() -> new BaseException(UserErrorCode.USER_NOT_FOUND));
Long userId = userFromDb.getId();
// 페이징 정의
Pageable pageable = PageRequest.of(page, size);
// DB에서 사용자id로 조회
Page<Loan> pageResultDTO = loanRepository.findByUser_Id(userId, pageable);
// pageDTO를 List형태로 변환
List<UserLoanListResDTO> listDTO = pageResultDTO.getContent()
.stream()
.map(UserLoanListResDTO::new)
.toList();
// listDTO를 PageImpl로 랩핑하여 반환
return new PageImpl<>(listDTO, pageResultDTO.getPageable(), pageResultDTO.getTotalElements());
}
4. LoanRepository
- userId와 pageable로 도서 대출 내역 조회하는 메서드 정의
// 사용자 도서 대출 내역 조회: userId로 조회
Page<Loan> findByUser_Id(Long userId, Pageable pageable);
5. SecurityConfig
- /api/v1/user/me/** HTTP 인가 설정에 URI 추가.
- 개발의 편의성을 위해 .permitAll()로 설정.
- 나중에 권한 세분화하기.
.authorizeHttpRequests(auth -> auth
.requestMatchers("/api/v1/user/me/**").permitAll()
.anyRequest().authenticated())