์ด๋ฒ์ ํ๋ก์ ํธ๋ฅผ ์งํํ๋ฉด์ ํํฐ๋๊ป ํน์ ์์
์ ์ํํ ๋ requestDto์ ๊ฐ์ ๊ทธ๋๋ก ๋๊ธฐ์ง ๋ง๊ณ command์ ๋ด์์ ๋๊ธฐ๋ ๊ฒ์ด ๋ ์ข๋ค๋ ํผ๋๋ฐฑ์ ๋ฐ์๋ค.
์ฒ์ ํผ๋๋ฐฑ์ ๋ฐ์์๋๋ reqeustDto์ command๋ฅผ ๋๋๋ ๊ตฌ๋ถ์ด ์ ์ดํด๊ฐ์ง ์์๊ธฐ ๋๋ฌธ์ ํด๋น ๋ถ๋ถ์ ์ ๋ฆฌํด๋ณด๊ณ ์ ํ๋ค.
์์)
// ์ ๋ฌ๋ฐ์ ๋ฐ์ดํฐ๋ฅผ ์ ๋ฌํ๋ ์ญํ
@Getter
public class CommentRequestDto {
private Long todoId;
private String content;
}
๐ ์์)
// ์ด๋ค์ฌ์ฉ์๊ฐ ์ด๋ค ์ผ์ ์ ์ด๋ค ๋๊ธ์ ์์ฑํ ๊ฒ์ธ์ง ๋ฑ์ ๋ฐ์ดํฐ๋ฅผ ํฌํจ
@Getter
@AllArgsConstructor
public class CreateCommentCommand {
private Long todoId;
private String content;
private Long memberId;
}
command์ dto์ ๊ตฌ๋ถ์ด ์ด๋์ ๋ ์ดํด๋ ๋์๋ค. ๊ทธ๋ ๋ค๋ฉด ๋ง์ฝ requestDto๋ง ์ฌ์ฉํ๋ค๋ฉด ์ด๋ค ๋ฌธ์ ๊ฐ ์๊ธธ๊น?
requestDto๋ง ์ฌ์ฉํ ๊ฒฝ์ฐ, ์๋น์ค ๊ณ์ธต์์ requestDto์ ๋ฐ์ดํฐ ๋ฟ๋ง์๋๋ผ ๋ค๋ฅธ ๋ฐ์ดํฐ ๊ฐ์ด ํ์ํ ๊ฒฝ์ฐ ๋ณ๋๋ก ๊ด๋ฆฌํด์ค์ผํ๊ธฐ ๋๋ฌธ์ ์ฝ๋๊ฐ ์ง์ ๋ถํด ์ง ์ ์์
๐ ์์)
// requestDto๋ง ์ฌ์ฉํ ๊ฒฝ์ฐ
// memberId ๋ณ๋๋ก ๊ด๋ฆฌํด์ผํจ
public CommentResponseDto save(Long memberId, CommentRequestDto commentRequestDto) {
Member findMember = memberRepository.getReferenceById(memberId);
Todo todo = todoRepository.findById(commentRequestDto.getTodoId())
.orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "ํ ์ผ ์ ๋ณด๋ฅผ ๋ค์ ์กฐํํด ์ฃผ์ธ์"));
Comment comment = new Comment(commentRequestDto.getContent(), findMember, todo);
commentRepository.save(comment);
return new CommentResponseDto(comment.getId(),
comment.getTodo().getId(),
comment.getContent(),
comment.getMember().getId(),
comment.getMember().getUsername(),
comment.getCreatedAt());
}
// command๋ฅผ ๋ถ๋ฆฌํ ๊ฒฝ์ฐ
public CommentResponseDto save(CreateCommentCommand command) {
Member findMember = memberRepository.getReferenceById(command.getMemberId());
Todo todo = todoRepository.findById(command.getTodoId())
.orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "ํ ์ผ ์ ๋ณด๋ฅผ ๋ค์ ์กฐํํด ์ฃผ์ธ์"));
Comment comment = new Comment(command.getContent(), findMember, todo);
commentRepository.save(comment);
return CommentResponseDto.toDto(comment);
}
dto
์ ๋ก์ง์ด ์ ์ ์ปค์ง๊ณ ๋ณต์กํด์ง ๊ฐ๋ฅ์ฑ์ด ์กด์ฌํจCommand
๋ก ๋ณ๋ ๊ด๋ฆฌํ๋ฉด ๊ฐ๊ฐ์ ์ญํ ์ ๋ถ๋ฆฌํ์ฌ ๊ด๋ฆฌํ๊ธฐ ๋๋ฌธ์ ์ฝ๋ ๋ณ๊ฒฝ์ด ์ฉ์ด
๋ฐ๋ผ์ ํด๋น ํด๋์ค๋ก dto์์ ์ญํ์ ๋ถ๋ฆฌํ์ฌ ์ฌ์ฉํ๋ ๊ฒ์ด ๋น์ฆ๋์ค ๋ก์ง์ ์ญํ ์ ๋ช ํํ๊ฒ ๊ตฌ๋ถํด์ฃผ๋ฉฐ, ์ดํ ์ ์ง๋ณด์ ์ธก๋ฉด์์๋ ๋์์ด ๋๋ฏ๋ก ๋ณ๋๋ก ์์ฑํ์ฌ ํ๋ก์ ํธ๋ฅผ ๋ง๋๋ ๊ฒ์ด ๋ฐ๋์งํ๋ค!