서비스
- 댓글을 저장하는 서비스 코드
- 파라미터가 많아져 관리와 가독성이 떨어질 경우
saveWithParams
사용
@Transactional
public void save(Long styleId, String content, Long memberId) {
Style style = styleRepository.findById(styleId)
.orElseThrow(() -> new SmException(ReturnCode.POST_NOT_FOUND));
Member member = memberRepository.findById(memberId)
.orElseThrow(() -> new SmException(ReturnCode.MEMBER_NOT_FOUND));
Comment comment = Comment.builder()
.member(member)
.style(style)
.content(content)
.build();
commentRepository.save(comment);
}
@Transactional
public void saveWithParams(SaveCommentParam param) {
Style style = styleRepository.findById(param.getStyleId())
.orElseThrow(() -> new SmException(ReturnCode.POST_NOT_FOUND));
Member member = memberRepository.findById(param.getMemberId())
.orElseThrow(() -> new SmException(ReturnCode.MEMBER_NOT_FOUND));
Comment comment = param.toEntity(style, member);
commentRepository.save(comment);
}
package project.stylemate.dto.params;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import project.stylemate.entity.Comment;
import project.stylemate.entity.Member;
import project.stylemate.entity.Style;
@Getter
@AllArgsConstructor
@Builder
@NoArgsConstructor
public class SaveCommentParam {
private Long memberId;
private String content;
private Long styleId;
public Comment toEntity(Style style, Member member) {
return Comment.builder()
.style(style)
.member(member)
.content(content)
.build();
}
}
컨트롤러
@PostMapping("/api/v1/styles/{styleId}/comments")
public ApiResponse<?> save(@PathVariable Long styleId, @RequestBody SaveCommentRequest saveCommentRequest) {
Long memberId = 1L;
commentService.save(styleId, saveCommentRequest.getContent(), memberId);
return ApiResponse.of(ReturnCode.SUCCESS);
}
@PostMapping("/api/v2/styles/{styleId}/comments")
public ApiResponse<?> saveWithParams(@PathVariable Long styleId, @RequestBody SaveCommentRequest saveCommentRequest) {
Long memberId = 1L;
SaveCommentParam param = saveCommentRequest.convert(styleId, memberId);
commentService.saveWithParams(param);
return ApiResponse.of(ReturnCode.SUCCESS);
}
- SaveCommentParam으로 변환하는 로직 보유
package project.stylemate.dto;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import project.stylemate.dto.params.SaveCommentParam;
@Getter
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class SaveCommentRequest {
private String content;
public SaveCommentParam convert(Long styleId, Long memberId) {
return SaveCommentParam.builder()
.content(content)
.styleId(styleId)
.memberId(memberId)
.build();
}
}