728x90
Swagger 에서 Pageable 이용하기
@RequestMapping("/stores")
@Api(tags = "store")
@RestController
public class StoreController {
@ApiOperation(value = "메뉴 조회 with paging", notes="store의 id를 이용하여 가맹점의 메뉴를 페이징 처리하여 조회합니다.")
@GetMapping(value="/{storeId}/menus")
public Map<String, Object> findAllMenuByMenuId(@ApiParam(name="storeId", value="store 테이블 id", required=true) @PathVariable("storeId") long storeId,
@PageableDefault(size=5, sort="name", direction = Sort.Direction.ASC) Pageable pageable) {
return storeService.findAllMenuByStoreId(storeId, pageable);
}
}
http://localhost:8080/stores/1/menus?page=1&size=3 의 조회결과는 아래와 같다.
{
result: "success",
storeName: "죠스떡볶이",
menus: [{
price: 2000,
name: "오뎅",
id: 2
}, {
price: 4000,
name: "치즈떡볶이",
id: 3
}, {
price: 2000,
name: "쿨피스",
id: 6
}
],
storeId: 1
}
JpaRepository가 상속받고 있는 PagingAndSortRepository에서는 Pageable 구현 클래스를 인자로 받아 정렬, 페이징 처리를 쉽게 처리해 줍니다.
이 기능을 swagger를 이용해서 api를 사용해보고 싶을 겁니다.
그런데 두둥!!
swagger에서 Pageable인자를 받는 api에서 page, size 가 아닌 pageNumber, pageSize 라는 이름으로 들어있어요.
그래서 실행시 에러가 납니다 😢
swagger에서 pageable 인자를 받고 싶다면 어떻게 해야할까요?
Swagger 설정 JavaConfig 에 AlternateTypeRules 을 설정해주면 됩니다.
바로 이렇게!
// DI 해줘야한다.
private final TypeResolver typeResolver;
@Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.alternateTypeRules(
AlternateTypeRules.newRule(typeResolver.resolve(Pageable.class), typeResolver.resolve(Page.class)))
.groupName("jiniworld")
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.jiniworld.test.controllers"))
.paths(PathSelectors.any())
.build();
}
@Getter @Setter
@ApiModel
static class Page {
@ApiModelProperty(value = "페이지 번호(0..N)")
private Integer page;
@ApiModelProperty(value = "페이지 크기", allowableValues="range[0, 100]")
private Integer size;
@ApiModelProperty(value = "정렬(사용법: 컬럼명,ASC|DESC)")
private List<String> sort;
}
위와 같은 대체룰을 설정 한 후, swagger 화면입니다.😄
출처: https://blog.jiniworld.me/20 [hello jiniworld]
출처: https://blog.jiniworld.me/20 [hello jiniworld]
728x90
'백엔드 > Spring(Boot)' 카테고리의 다른 글
스프링 시큐리티 OAuth 2.0 (0) | 2022.03.17 |
---|---|
스프링 Rest Template (0) | 2022.03.16 |
Spring Data Jpa repository 통합 (0) | 2022.02.23 |
InitDB 하는 법 (0) | 2022.02.22 |
swagger 파라미터 안보이게 하기 (0) | 2022.01.21 |