[spring boot] 게시글 등록/수정/삭제/조회 API 만들기 - 07

Momenter·2021년 7월 21일
0

Spring Boot

목록 보기
12/15

게시글 삭제

index.js delete function 추가

var main = {
    init : function () {
        var _this = this;
        $('#btn-save').on('click', function () {
            _this.save();
        });

        $('#btn-update').on('click', function () {
            _this.update();
        });

        $('#btn-delete').on('click', function () {
            _this.delete();
        });
    },
    save : function () {
        var data = {
            title: $('#title').val(),
            author: $('#author').val(),
            content: $('#content').val()
        };

        $.ajax({
            type: 'POST',
            url: '/api/v1/posts',
            dataType: 'json',
            contentType:'application/json; charset=utf-8',
            data: JSON.stringify(data)
        }).done(function() {
            alert('글이 등록되었습니다.');
            window.location.href = '/';
        }).fail(function (error) {
            alert(JSON.stringify(error));
        });
    },
    update : function () {
        var data = {
            title: $('#title').val(),
            content: $('#content').val()
        };

        var id = $('#id').val();

        $.ajax({
            type: 'PUT',
            url: '/api/v1/posts/'+id,
            dataType: 'json',
            contentType:'application/json; charset=utf-8',
            data: JSON.stringify(data)
        }).done(function() {
            alert('글이 수정되었습니다.');
            window.location.href = '/';
        }).fail(function (error) {
            alert(JSON.stringify(error));
        });
    },
    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();

게시글 삭제 API 작성

PostsService 추가 작성

package com.momenting.book.springboot.service.posts;

import com.momenting.book.springboot.domain.posts.Posts;
import com.momenting.book.springboot.domain.posts.PostsRepository;
import com.momenting.book.springboot.web.dto.PostsListResponseDto;
import com.momenting.book.springboot.web.dto.PostsResponseDto;
import com.momenting.book.springboot.web.dto.PostsSaveRequestDto;
import com.momenting.book.springboot.web.dto.PostsUpdateRequestDto;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

@RequiredArgsConstructor
@Service
public class PostsService {

    private final PostsRepository postsRepository;

    @Transactional(readOnly = true)
    public List<PostsListResponseDto> findAllDesc() {
        return postsRepository.findAllDesc().stream().map(PostsListResponseDto::new).collect(Collectors.toList());
    }

    @Transactional
    public Long save(PostsSaveRequestDto requestDto) {
        return postsRepository.save(requestDto.toEntity()).getId();
    }

    @Transactional
    public Long update(Long id, PostsUpdateRequestDto requestDto) {

        Posts posts = postsRepository.findById(id).orElseThrow(() -> new IllegalArgumentException("해당 게시글이 없습니다. id =" + id));
        posts.update(requestDto.getTitle(), requestDto.getContent());

        return id;
    }

    @Transactional //<-@@
    public void  delete(Long id) {
        Posts posts = postsRepository.findById(id).orElseThrow(() -> new IllegalArgumentException("해당 게시글이 없습니다. id=" + id));
        postsRepository.delete(posts); //JpaRepository에서 제공하고 있는 delete 메소드 사용
    } //<-@@

    public PostsResponseDto findById (Long id) {
        Posts entity = postsRepository.findById(id).orElseThrow( () -> new IllegalArgumentException("해당 게시글이 없습니다. id =" + id));

        return  new PostsResponseDto(entity);
    }
}

PostsApiController 추가 작성

package com.momenting.book.springboot.web;


import com.momenting.book.springboot.service.posts.PostsService;
import com.momenting.book.springboot.web.dto.PostsResponseDto;
import com.momenting.book.springboot.web.dto.PostsSaveRequestDto;
import com.momenting.book.springboot.web.dto.PostsUpdateRequestDto;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

@RequiredArgsConstructor
@RestController
public class PostsApiController {

    private final PostsService postsService;

    @PostMapping("/api/v1/posts")
    public Long save (@RequestBody PostsSaveRequestDto requestDto) {
        return postsService.save(requestDto);
    }

    @PutMapping("/api/v1/posts/{id}")
    public Long update(@PathVariable Long id, @RequestBody PostsUpdateRequestDto requestDto) {
        return  postsService.update(id, requestDto);
    }

    @DeleteMapping("/api/v1/posts/{id}") // <-@@
    public Long delete(@PathVariable Long id) {
        postsService.delete(id);
        return id;
    } // <-@@

    @GetMapping("/api/v1/posts/{id}")
    public PostsResponseDto findById (@PathVariable Long id) {
        return postsService.findById(id);
    }

}
  • // <-@@로 표시된 구문이 이번 포스팅에서 추가 작성된 구문입니다.

브라우저에서 기능 확인하기

  • 글 목록 확인

  • 삭제할 게시글 상세조회

-삭제 및 목록 획인

profile
순간을 기록하는 개발자

0개의 댓글