-
Notifications
You must be signed in to change notification settings - Fork 8
[9주차/박콩] 워크북 제출합니다 #46
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
base: parkkong/main
Are you sure you want to change the base?
Conversation
kfdsy0103
left a comment
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
9주차 워크북 수행하시느라 고생많으셨어요 박콩!
리뷰 확인 후 머지해주시면 됩니다~
| public interface ReviewControllerDocs { | ||
| @Operation( | ||
| summary = "가게의 리뷰 목록 조회 API By 박콩(개발 중)", | ||
| description = "특정 가게의 리뷰를 모두 조회합니다. 페이지네이션으로 제공합니다." | ||
| ) | ||
| @ApiResponses({ | ||
| @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "200",description = "성공"), | ||
| @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "400", description = "실패") | ||
| }) | ||
| @Parameters({ | ||
| @Parameter(name="storeName", description = "가게 이름"), | ||
| @Parameter(name="page",description = "페이지 번호") | ||
| }) | ||
| ApiResponse<ReviewResDTO.ReviewPreViewListDTO> getReviews( | ||
| @RequestParam(name="storeName") String storeName, | ||
| @RequestParam(name="page") Integer page | ||
| ); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
옹 이렇게 인터페이스 만들어서 docs 관리하는 거 진짜 좋아보이네요
| import java.util.Optional; | ||
|
|
||
| public interface StoreRepository extends JpaRepository<Store, Long> { | ||
| Optional<Store> findByName(String name); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Optional 감싸주기 구시에요
| //내 리뷰 목록(페이징 정보 포함) | ||
| @Builder | ||
| public record MyReviewPreviewListDTO( | ||
| List<ReviewPreviewWorkbookDTO> reviewList, | ||
| Integer listSize, | ||
| Integer totalPage, | ||
| Long totalElements, | ||
| Boolean isFirst, | ||
| Boolean isLast | ||
| ){} |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
페이징이 Review 뿐만 아니라 다른 도메인에서도 적용될 수 있잖아요?
그러면 위와 같은 구조의 페이징 응답용 DTO를 매번 작성해야할 거 같아요. 아래처럼요!
// 리뷰
@Builder
public record MyReviewPreviewListDTO(
List<단건 DTO> list,
Integer listSize,
Integer totalPage,
Long totalElements,
Boolean isFirst,
Boolean isLast
){}
// 미션
@Builder
public record MyMissionPreviewListDTO(
List<단건 DTO> list,
Integer listSize,
Integer totalPage,
Long totalElements,
Boolean isFirst,
Boolean isLast
){}
// 기타...
@Builder
public record somethingDomainPageDTO (
List<단건 DTO> list,
Integer listSize,
Integer totalPage,
Long totalElements,
Boolean isFirst,
Boolean isLast
){}대부분 코드 구조가 비슷하니까 아래처럼 '공통 페이징 응답용 DTO' 를 따로 만들어줘도 괜찮아보이네용
@Getter
@Builder
public class CommonPageResponse<T> {
private List<T> content; // 데이터 리스트
private int totalPages; // 전체 페이지 수
private long totalElements; // 전체 요소 수
private int currentPage; // 현재 페이지 번호
private int size; // 한 페이지당 크기
private boolean hasNext; // 다음 페이지 존재 여부
public static <T> CommonPageResponse<T> of(Page<T> page) {
return CommonPageResponse.<T>builder()
.content(page.getContent())
.totalPages(page.getTotalPages())
.totalElements(page.getTotalElements())
.currentPage(page.getNumber())
.size(page.getSize())
.hasNext(page.hasNext())
.build();
}
}이러면 박콩이 작성해주신 MyReviewPreviewListDTO는 없애도 되고,
위 '공통 페이징 응답용 DTO'로 컨트롤러에서 한번 더 감싸주는 방식으로 짜면 될 거예요!
아래처럼 말이죠!
// controller
public ApiResponse<CommonPageResponse<ReviewPreviewDTO>> method(...) {
Page<ReviewPreviewDTO> pageDTO = service.getPage(...);
CommonPageResponse<ReviewPreviewDTO> response = CommonPageResponse.of(pageDTO);
return ApiReponse.ok(response);
}아니면 다른 방안으로는 ApiResponse에 메타정보를 넣는다거나... 하는 방식으로 코드 중복을 제거해볼 수도 있겠네요.
참고만 하시기 바랍니다!!
| @Builder | ||
| public record ReviewPreViewListDTO( | ||
| List<ReviewPreviewDTO> reviewList, | ||
| Integer listSize, | ||
| Integer totalPage, | ||
| Long totalElements, | ||
| Boolean isFirst, | ||
| Boolean isLast | ||
| ){} |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
공통 페이징 응답 DTO로 적용하신다면 이것도 지워도 되겠네요.
| @GetMapping("/my") | ||
| public ApiResponse<List<ReviewResDTO.ReviewPreviewDTO>>getMyReviews( | ||
| public ApiResponse<List<ReviewResDTO.ReviewPreviewWorkbookDTO>>getMyReviews( | ||
| @RequestParam(name = "userId")Long userId, |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
스터디 때 userId 어떻게 받아오냐고 여쭤보셨던 거 같아요!
방법은 찾아보시면 여러가지 있는데, 제가 알고있는 방식만 대략 설명드릴게요!
- JWT에서 userId를 추출하고 ArgumentResolver를 커스텀하여 컨트롤러 인자로 받기
스프링 시큐리티 단에서 JWT 유효성 검증을 마치면, JWT로 부터 userId를 추출하여 컨트롤러의 인자로 바로 넘겨주는 방식이에요.
이때 컨트롤러가 필요로 하는 인자를 만들어주는건 ArgumentResolver 의 역할이잖아요? 그래서 이걸 직접 커스텀해야해요.
// 1. 커스텀 어노테이션 정의 (@UserId)
@Target(ElementType.PARAMETER)
@Retention(RetentionPolicy.RUNTIME)
@Parameter(hidden = true) // Swagger UI hidden
public @interface UserId {
}// 2. ArgumentResolver 커스텀
@Component
public class UserIdArgumentResolver implements HandlerMethodArgumentResolver {
// 어떤 어노테이션에 적용될 리졸버인지 (위에서 정의한 @UserId)
@Override
public boolean supportsParameter(MethodParameter parameter) {
return parameter.hasParameterAnnotation(UserId.class);
}
// 어떤 값을 전달하면 되는지
@Override
public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer,
NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
return (Long)authentication.getDetails();
}
}// 3. 사용하는 컨트롤러 쪽에서는 어노테이션만 적용
public ApiResponse<...> method(
@UserId Long userId
) {...}보통 경험 많으신 분들이 위처럼 만들어주실 거예요.
물론 다른 방법도 있겠지만, '이런 방법이 있다!' 로만 이해해주세요!
✅ 실습 체크리스트
✅ 컨벤션 체크리스트
📌 주안점