// posts-update.mustache
{{>layout/header}}
<h1>게시글 수정</h1>
<div class="col-md-12">
...
<button type="button" class="btn btn-primary" id="btn-update">수정 완료</button>
// btn-danger : 삭제 버튼을 수정 완료 버튼 옆에 추가한 후 해당 버튼 클릭 시 JS에서 이벤트를 수신
<button type="button" class="btn btn-danger" id="btn-delete">삭제</button>
</div>
</div>
{{>layout/footer}}
index.js 코드 추가 : 삭제 이벤트를 진행할 JS 코드 추가
// index.js
var main = {
init : function () {
...
$('#btn-delete').on('click', function () {
_this.delete();
});
},
save : function () {
...
},
update : function () {
...
},
delete : function () {
var id = $('#id').val();
$.ajax({
type: 'DELETE',
url: '/api/v1/posts/'+id,
dataType: 'json',
contentType:'application/json; charset=utf-8'
}).done(function() {
alert('글이 삭제되었습니다.');
window.location.href = '/';
}).fail(function (error) {
alert(JSON.stringify(error));
});
}
};
main.init();
PostsService에 코드 추가 : 삭제 API 생성을 위한 서비스 메소드
// PostsService.java
@Transactional
public void delete(Long id) {
Posts posts = postsRepository.findById(id).orElseThrow(() -> new IllegalArgumentException("해당 게시글이 없습니다. id=" + id));
/* JpaRepository에서 지원하는 delete 메소드 활용
엔티티를 파라미터로 삭제할 수도 있고, deleteById 메소드를 이용하면 id로 삭제할 수 있음
존재하는 Posts인지 확인을 위해 엔티티 조회 후 그대로 삭제 */
postsRepository.delete(posts);
}
PostsApiController에 코드 추가 : 서비스에서 만든 delete 메소드를 컨트롤러가 사용하도록 코드 추가
// PostsApiController.java
@DeleteMapping("/api/v1/posts/{id}")
public Long delete(@PathVariable Long id) {
postsService.delete(id);
return id;
}