今天將會實作 Comment 更新資料的 function API,
在 CommentService.java 中加上 updateComment 的 method
public interface CommentService {
CommentDto createComment(long postId, CommentDto commentDto);
List<CommentDto> getCommentsByPostId(long postId);
CommentDto getCommentById(long postId, long commentId);
CommentDto updateComment(long postId, long commentId, CommentDto commentRequest);
}
會要等 loader 的來能處理
在 CommentServiceImpl.java 中建立使用實例
@Override
public CommentDto updateComment(long postId, long commentId, CommentDto commentRequest){
Post post = postRepository.findById(postId).orElseThrow(() -> new ResourceNotFoundExceptiom("Post","id",postId));
Comment comment = commentRepository.findById(commentId).orElseThrow(() ->
new ReaourceNotFoundException("Comment","id",commentId);
if(!comment.getPost().getId().equals(post.getId())){
throw new BlogAPIEXCEPTION(HttpStatus.BAD_REQUEST, "Comment does not belongs to post");"
}
comment.setName(commentRequest.getName());
comment.setEmail(commentRequest.getEmail());
comment.setBody(commentRequest.getBody());
Comment updateComment = commentRepository.save(comment);
return mapToDTO(updateComment);
}
CommentController.java
@PutMapping("/posts/{postId}/comments/{id}")
public RepositoryEntity<CommentDto> updateComment(@ParthVariable(value="postId" long postId,
@RequestBody CommentDto commentDto){
return new ResponseEntity<>(commentService.createComment(postId,commentDto), HttpStatus.CREATED);
一樣在 Postman 中,這次是作 http”//localhost:8080/api/posts/1/comments/1
貼上原本有使用的 JSON 內容,之後改動內容,則需要轉換成 PUT