개발일지/2023_한이음
[개발]🤦🏻♀️고민하기 - review 기능에 커스텀 DTO 적용
기억지기 개발자
2023. 6. 17. 21:46
@PostMapping()
public ResponseEntity<Review> save(@RequestBody ReviewDTO reviewdto) {
School school = schoolService.findBySchoolId(1L)
.orElseThrow(() -> new IllegalArgumentException("학교가 존재하지 않습니다."));
Review review = ReviewDTO.toEntity(reviewdto, school);
return ResponseEntity.ok().body(reviewService.save(review));
}
//해당 학교애 대한 전체 리뷰 보여주기
@GetMapping()
public ResponseEntity<List<Review>> getReviewsBySchoolId(@RequestParam(name = "schoolId") Long schoolId) {
School school = schoolService.findBySchoolId(schoolId)
.orElseThrow(() -> new IllegalArgumentException("학교가 존재하지 않습니다."));
List<Review> reviews = reviewService.findAll(school);
return ResponseEntity.ok(reviews);
}
//update
@PutMapping(value = "/{id}")
public ResponseEntity<Review> update(@RequestBody ReviewDTO dto, @PathVariable Long id) {
Optional<Review> reviewdto = this.reviewService.update(id, dto);
return new ResponseEntity(reviewdto, HttpStatus.OK);
}
//delete
@DeleteMapping(value = "/{id}")
public void delete(@PathVariable Long id) {
reviewService.delete(id);
}
➡️기존의 reviewController 코드
return repository.save(review);
}
public Optional<Review> findById(Long id){ //해당 학교 -> 학교에 해당하는 댓글 1개를 가져와서 update에 사용
Optional<Review> re = repository.findById(id);
return re;
}
public Optional<Review> update(Long id, ReviewDTO dto){
Optional<Review> entity = this.repository.findById(id);
entity.ifPresent(t ->{
// 내용이 널이 아니라면 엔티티의 객체를 바꿔준다.
if(dto.getContent() != null) {
t.setContent(dto.getContent());
}
if(dto.getTrafficRate() != null) {
t.setTrafficRate(dto.getTrafficRate());
}
if(dto.getFacilityRate() != null) {
t.setFacilityRate(dto.getFacilityRate());
}
if(dto.getCafeteriaRate() != null) {
t.setCafeteriaRate(dto.getCafeteriaRate());
}
if(dto.getEducationRate() != null) {
t.setEducationRate(dto.getEducationRate());
}
if(dto.getEmploymentRate() != null) {
t.setEmploymentRate(dto.getEmploymentRate());
}
// 이걸 실행하면 idx 때문에 update가 실행됩니다.
this.repository.save(t);
});
return entity;
}
public List<Review> findAll(School schoolId){ //학교 아이디를 가져와서 해당 학교에 대한 리뷰 전체를 보여줌
List<Review> re = repository.findBySchoolId(schoolId);
return re;
}
public void delete(Long id){
repository.deleteById(id);
}
➡️기존의 reviewService 코드
다른 백엔드 팀원이 만들어놓은 커스텀 DTO를 모든 메소드에 적용해 보기로 했다. 원래는 ResponseEntity <?>를 사용하기로 했지만.... 다시 방향을 바꿨다...
어떤 것이 더 좋은지는 프로젝트의 규모, 요구사항, 개발 스타일에 따라 다를 수 있습니다. 작은 프로젝트나 간단한 API에서는 ResponseEntity를 사용하는 것이 편리할 수 있습니다. 그러나 복잡한 API에서는 ResponseDTO와 같은 커스텀 응답 클래스를 사용하는 것이 일관성과 유지 보수성을 높일 수 있습니다.
따라서 개발 환경과 요구사항을 고려하여 어떤 방식이 프로젝트에 더 적합한지 판단하시면 됩니다.
정확히 무엇이 정답인지는 몰라도 커스텀 DTO를 사용해 보면 좀 더 다양한 경험을 할 수 있지 않을까.. 하는 기대를 가져보며😀
// 리뷰 등록
@PostMapping()
public ResponseDTO<?> save(@RequestBody ReviewDTO reviewdto) {
School school = schoolService.findBySchoolId(1L)
.orElseThrow(() -> new IllegalArgumentException("학교가 존재하지 않습니다."));
Review review = ReviewDTO.toEntity(reviewdto, school);
return reviewService.save(review);
}
//해당 학교애 대한 전체 리뷰 보여주기
@GetMapping()
public ResponseDTO<?> getReviewsBySchoolId(@RequestParam(name = "schoolId") Long schoolId) {
School school = schoolService.findBySchoolId(schoolId)
.orElseThrow(() -> new IllegalArgumentException("학교가 존재하지 않습니다."));
return reviewService.findAll(school);
}
//update
@PutMapping(value = "/{id}")
public ResponseDTO<?> update(@RequestBody ReviewDTO dto, @PathVariable Long id) {
return reviewService.update(id, dto);
}
//delete
@DeleteMapping(value = "/{id}")
public void delete(@PathVariable Long id) {
reviewService.delete(id);
}
➡️ResponseDTO 적용 후 코드
public ResponseDTO<?> save(Review review){
Review re = repository.save(review);
return ResponseDTO.success(re);
}
public Optional<Review> findById(Long id){ //해당 학교 -> 학교에 해당하는 댓글 1개를 가져와서 update에 사용
Optional<Review> re = repository.findById(id);
return re;
}
public ResponseDTO<?> update(Long id, ReviewDTO dto){
Optional<Review> entity = this.repository.findById(id);
entity.ifPresent(t ->{
// 내용이 널이 아니라면 엔티티의 객체를 바꿔준다.
if(dto.getContent() != null) {
t.setContent(dto.getContent());
}
if(dto.getTrafficRate() != null) {
t.setTrafficRate(dto.getTrafficRate());
}
if(dto.getFacilityRate() != null) {
t.setFacilityRate(dto.getFacilityRate());
}
if(dto.getCafeteriaRate() != null) {
t.setCafeteriaRate(dto.getCafeteriaRate());
}
if(dto.getEducationRate() != null) {
t.setEducationRate(dto.getEducationRate());
}
if(dto.getEmploymentRate() != null) {
t.setEmploymentRate(dto.getEmploymentRate());
}
// 이걸 실행하면 idx 때문에 update가 실행됩니다.
this.repository.save(t);
});
return ResponseDTO.success(entity);
}
public ResponseDTO<?> findAll(School schoolId){ //학교 아이디를 가져와서 해당 학교에 대한 리뷰 전체를 보여줌
List<Review> re = repository.findBySchoolId(schoolId);
return ResponseDTO.success(re);
}
public ResponseDTO<?> delete(Long id){
repository.deleteById(id);
return ResponseDTO.success("delete success");
}
➡️ResponseDTO 적용 후 코드
update 기능 부분이 코드가 다소 지저분... 해 보이기도 하고 좀 더 신기술(?)인 '더디체킹' 방식이 있다고 해서 추후 곧바로 적용해 볼 예정이다.
