항해99/스프링 심화

주특기 심화 댓글 기능 구현2 - 석준매니저님

숲별 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.entity.Post;
import com.example.spring_subject.repository.CommentRepository;
import com.example.spring_subject.repository.PostRepository;
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, @AuthenticationPrincipal UserDetailsImpl userDetailsImpl){
        Post post = postRepository.findById(commentRequestDto.getPostid()).orElseThrow(
                ()->new IllegalArgumentException("아이디가 존재하지 않습니다.")
        );
        Comment comment = new Comment(commentRequestDto, post, userDetailsImpl.getAccount ());
        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 = this.commentRepository.findById(id).orElseThrow(() -> new IllegalArgumentException("해당 댓글이 없습니다."));
        String email = comment.getAccount ().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 = this.commentRepository.findById(id).orElseThrow(()->new IllegalArgumentException("id가 없습니다."));
        String email = comment.getAccount ().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;
}

 

 

 

 

 

 

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;


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

    @ManyToOne
    @JoinColumn(name = "account_id")
    private Account account;

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

    public void update(CommentRequestDto requestDto){
        this.comment = requestDto.getComment();
    }
}

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

AWS S3 IAM SDK  (1) 2022.10.23
석준 매니저님 멘토링 메모  (0) 2022.10.22
주특기 심화 댓글 기능 구현 1  (0) 2022.10.18
재영매니저님 강의  (0) 2022.10.17
좋아요 기능 참고 링크  (0) 2022.10.17