항해99/스프링 심화

주특기 심화 댓글 기능 구현 1

숲별 2022. 10. 18. 21:59
728x90
package com.example.spring_subject.controller;

import com.example.spring_subject.dto.CommentRequestDto;
import com.example.spring_subject.entity.Comment;
import com.example.spring_subject.repository.CommentRepository;
import com.example.spring_subject.security.user.UserDetailsImpl;
import com.example.spring_subject.service.CommentService;
import lombok.RequiredArgsConstructor;
import org.aspectj.weaver.Member;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RequiredArgsConstructor
@RestController
@RequestMapping("/api")
public class CommentController {
    private final CommentRepository commentRepository;
    private final CommentService commentService;
    private final PostRepository postRepository;

    @PostMapping("/auth/comment")
    public Comment createComment(@RequestBody CommentRequestDto commentRequestDto){
        Post post = postRepository.findById(commentRequestDto.getPostid()).orElseThrow(
                ()->new IllegalArgumentException("아이디가 존재하지 않습니다.")
        );
        Comment comment = new Comment(commentRequestDto, post);
        return commentRepository.save(comment);
    }

    @GetMapping("/comment")
    public List<Comment> getComment(){return commentRepository.findAllByOrderByCreatedAtDesc();}


    @PutMapping("/auth/comment/{id}")
    public String updateComment(@PathVariable Long id, @RequestBody CommentRequestDto commentRequestDto, @AuthenticationPrincipal UserDetailsImpl userDetailsImpl ) throws Exception {
        Comment comment = commentRepository.findById(id).orElseThrow(() -> new IllegalArgumentException("해당 댓글이 없습니다."));
        String email = comment.getEmail();
        if(userDetailsImpl.getAccount().getEmail().equals(email)){
            commentService.update(id, commentRequestDto);
        }else {
            throw new Exception("사용자가 일치하지 않습니다.");
        }
        return "댓글 수정완료";
    }


    @DeleteMapping("/auth/comment/{id}")
    public String deleteComment(@PathVariable Long id, @AuthenticationPrincipal UserDetailsImpl userDetailsImpl) throws Exception {

        Comment comment = commentRepository.findById(id).orElseThrow(()->new IllegalArgumentException("id가 없습니다."));
        String email =comment.getEmail();
        if(userDetailsImpl.getAccount().getEmail().equals(email)){
            commentRepository.deleteById(id);
        }else {throw new Exception("사용자가 일치하지 않습니다.");
        }
        return  "댓글삭제완료";
    }

}
package com.example.spring_subject.dto;

import lombok.Getter;

@Getter
public class CommentRequestDto {
    private Long postid;
    private String comment;
    private String email;
}
package com.example.spring_subject.entity;

import com.example.spring_subject.dto.CommentRequestDto;
import com.example.spring_subject.jwt.filter.JwtAuthFilter;
import com.example.spring_subject.jwt.util.JwtUtil;
import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.Getter;
import lombok.NoArgsConstructor;

import javax.persistence.*;

@Getter
@NoArgsConstructor
@Entity

public class Comment extends Timestamped{
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Id
    private Long id;

    @Column(nullable = false)
    private String comment;
    @Column(nullable = false)
    private String email;

    @ManyToOne
    @JsonIgnore
    @JoinColumn(name = "post_id")
    private Post post;

    public Comment(CommentRequestDto commentRequestDto, Post post){
        this.comment = commentRequestDto.getComment();
        this.post = post;
        this.email=post.getEmail();
    }

    public void update(CommentRequestDto requestDto){
        this.comment = requestDto.getComment();
    }
}
package com.example.spring_subject.repository;

import com.example.spring_subject.entity.Comment;
import org.springframework.data.jpa.repository.JpaRepository;

import java.util.List;

public interface CommentRepository extends JpaRepository <Comment, Long>{
    List<Comment> findAllByOrderByCreatedAtDesc();
}
package com.example.spring_subject.service;

import com.example.spring_subject.dto.CommentRequestDto;
import com.example.spring_subject.entity.Comment;
import com.example.spring_subject.repository.CommentRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;

@RequiredArgsConstructor
@Service
public class CommentService {
    private final CommentRepository commentRepository;
    @Transactional
    public Long update(Long postid, CommentRequestDto requestDto){
        Comment comment = commentRepository.findById(postid).orElseThrow(
                () -> new IllegalArgumentException("게시글이 존재하지 않습니다.")
        );
        comment.update(requestDto);
        return comment.getId();
    }
}

'항해99 > 스프링 심화' 카테고리의 다른 글

석준 매니저님 멘토링 메모  (0) 2022.10.22
주특기 심화 댓글 기능 구현2 - 석준매니저님  (0) 2022.10.18
재영매니저님 강의  (0) 2022.10.17
좋아요 기능 참고 링크  (0) 2022.10.17
항해 4주차 WIL  (0) 2022.10.16