Application/Test
[Postman][5] PUT- 카테고리 수정(컨트롤러 요청메세지 테스트)
Kangjieun11
2022. 12. 20. 20:58
728x90
카테고리 수정하는 부분에서 PATCH를 사용하면서 문제가 있었는데,
좀 알아보니까 PATCH용 DTO를 따로 만들고 그러는것 같다..
카테고리에서 굳이 그럴 필요까지는 없을 것 같아서 PUT으로 바꾸고 테스트를 진행해야겠다.
나중에 PATCH를 쓰는건 연습을 따로 해봐야지..
✅ GIVEN
일단 data 입력해주고,
id가 5인 카테고리의 이름 "카테고리4"를 "ALGORITHM"으로 바꾸기!
PUT으로 바꿨기 떄문에 전체 데이터를 보내준다.
PUT http://localhost:8080/v1/categories/5
{
"name":"ALGORITHM",
"categoryDepth":2,
"parentId":3
}
PATCH는 참고할만한 예제가 많이 없어서 연습이 필요할 듯 하다 ㅠㅠ
✅ 결과 확인
잘 바뀌었다..!
💻 Controller
@PutMapping("/{categoryId}")
public ResponseEntity updateCategory(@PathVariable long categoryId,
@RequestBody CategoryDto categoryDto) {
categoryDto.setId(categoryId);
categoryService.updateCategory(categoryDto);
return new ResponseEntity(HttpStatus.OK);
}
💻 Service
@Transactional
public void updateCategory (CategoryDto categoryDto) {
Category category = categoryRepository.findById(categoryDto.getId()).orElse(null);
if(category == null) {
throw new CustomException(ErrorCode.CATEGORY_NOT_EXISTS);
}
Category parentCategory = null;
if (categoryDto.getCategoryDepth() > 0){
parentCategory = categoryRepository.findById(categoryDto.getParentId()).orElse(null);
}
category.setName(categoryDto.getName());
category.setParent(parentCategory);
category.setCategoryDepth(categoryDto.getCategoryDepth());
}
나중에 참고할 내용
✔️ PUT, PATCH 사용 관련
https://www.baeldung.com/http-put-patch-difference-spring