Skip to content

Commit

Permalink
Merge pull request #140 from inje-megabrain/feat/post_api
Browse files Browse the repository at this point in the history
Feat/post api
  • Loading branch information
sleeg00 authored Mar 19, 2024
2 parents 3503b4f + c753139 commit c9672ba
Show file tree
Hide file tree
Showing 9 changed files with 243 additions and 95 deletions.
54 changes: 54 additions & 0 deletions src/main/generated/com/example/just/Dao/QPostLike.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
package com.example.just.Dao;

import static com.querydsl.core.types.PathMetadataFactory.*;

import com.querydsl.core.types.dsl.*;

import com.querydsl.core.types.PathMetadata;
import javax.annotation.processing.Generated;
import com.querydsl.core.types.Path;
import com.querydsl.core.types.dsl.PathInits;


/**
* QPostLike is a Querydsl query type for PostLike
*/
@Generated("com.querydsl.codegen.DefaultEntitySerializer")
public class QPostLike extends EntityPathBase<PostLike> {

private static final long serialVersionUID = -993289340L;

private static final PathInits INITS = PathInits.DIRECT2;

public static final QPostLike postLike = new QPostLike("postLike");

public final NumberPath<Long> id = createNumber("id", Long.class);

public final QMember member;

public final QPost post;

public QPostLike(String variable) {
this(PostLike.class, forVariable(variable), INITS);
}

public QPostLike(Path<? extends PostLike> path) {
this(path.getType(), path.getMetadata(), PathInits.getFor(path.getMetadata(), INITS));
}

public QPostLike(PathMetadata metadata) {
this(metadata, PathInits.getFor(metadata, INITS));
}

public QPostLike(PathMetadata metadata, PathInits inits) {
this(PostLike.class, metadata, inits);
}

public QPostLike(Class<? extends PostLike> type, PathMetadata metadata, PathInits inits) {
super(type, metadata, inits);
this.member = inits.isInitialized("member") ? new QMember(forProperty("member")) : null;
this.post = inits.isInitialized("post") ? new QPost(forProperty("post"), inits.get("post")) : null;
}

}

6 changes: 5 additions & 1 deletion src/main/java/com/example/just/Admin/AdminController.java
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
import com.example.just.Service.*;
import io.swagger.annotations.ApiOperation;
import io.swagger.v3.oas.annotations.Operation;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.data.crossstore.ChangeSetPersister.NotFoundException;
Expand Down Expand Up @@ -129,12 +130,15 @@ public ResponseEntity<List<Post>> PostList() {
@ApiOperation(value = "포스트페이지에서 포스트 삭제 ")
@Operation(summary = "게시글 삭제", description = "\n post_id 헤더로 받고 데이터베이스 비교 후 회원 삭제")
@DeleteMapping("/posts/{post_id}")
public ResponsePost deletePost(@PathVariable Long post_id) throws NotFoundException {
public ResponsePost deletePost(@PathVariable Long post_id, HttpServletRequest request) throws NotFoundException {

postService.deletePost(post_id);
ResponsePost responsePost = new ResponsePost(post_id, "삭제 완료");
return responsePost;
}



@ApiOperation(value = "포스트페이지 해시태그 수정 ")
@Operation(summary = "해시태그 수정", description = "\n hashtag_id 헤더로 받고 내용을 수정하면 새로운 해시태그를 생성하여 저장 ex) id_101 -> id_104로")
@PutMapping("/hashtags/{hashtag_id}")
Expand Down
30 changes: 20 additions & 10 deletions src/main/java/com/example/just/Controller/CommentController.java
Original file line number Diff line number Diff line change
Expand Up @@ -79,12 +79,12 @@ public ResponseEntity<ResponseCommentDto> createComment(@PathVariable Long post_
member_id = Long.valueOf(jwtProvider.getIdFromToken(token)); //토큰
comment = commentService.createComment(post_id, member_id, comment_dto);

} catch (NullPointerException e){
} catch (NullPointerException e) {
return ResponseEntity.status(404).body(new ResponseCommentDto("해당 부모 댓글 없음"));
} catch (RuntimeException e){
} catch (RuntimeException e) {
return ResponseEntity.status(404).body(new ResponseCommentDto("대댓글에는 대댓글 작성 불가"));
}
return ResponseEntity.ok(new ResponseCommentDto(comment,member_id,"입력 완료"));
return ResponseEntity.ok(new ResponseCommentDto(comment, member_id, "입력 완료"));
}

@ApiOperation(value = "댓글 조회 API")
Expand All @@ -102,20 +102,24 @@ public ResponseEntity<ResponsePostCommentDtoBefore> getCommentListBefore(@PathVa

@Operation(summary = "댓글 삭제 api", description = "대댓글까지 다 삭제되니 유의해야 함")
@DeleteMapping("/delete/comment/{post_id}/{comment_id}")
public ResponseEntity<String> deleteComment(@PathVariable Long post_id, @PathVariable Long comment_id) {
return commentService.deleteComment(post_id, comment_id);
public ResponseEntity<String> deleteComment(@PathVariable Long post_id, @PathVariable Long comment_id,
HttpServletRequest request) {
Long member_id = getAccessTokenOfMemberId(request);
return commentService.deleteComment(post_id, comment_id, member_id);
}


@ApiOperation(value = "댓글 수정")
@ApiResponses(value = {
@ApiResponse(responseCode = "200",description = "댓글 내용"),
@ApiResponse(responseCode = "400",description = "댓글이 존재하지 않습니다.\n게시물이 존재하지 않습니다.")
@ApiResponse(responseCode = "200", description = "댓글 내용"),
@ApiResponse(responseCode = "400", description = "댓글이 존재하지 않습니다.\n게시물이 존재하지 않습니다.")
})
@PutMapping("/put/comment/{post_id}/{comment_id}")
public ResponseEntity<String> putComment(@PathVariable Long post_id, @PathVariable Long comment_id,
@RequestBody PutCommentDto commentDto,
HttpServletRequest req) {
return commentService.putComment(post_id, comment_id, commentDto);
HttpServletRequest request) {
Long member_id = getAccessTokenOfMemberId(request);
return commentService.putComment(post_id, comment_id, commentDto, member_id);
}

@ApiOperation(value = "댓글 신고")
Expand Down Expand Up @@ -153,7 +157,7 @@ public ResponseEntity getMyComment(HttpServletRequest request) {
return commentService.getMyComment(member_id);
}

private String errorMassage(String error){
private String errorMassage(String error) {
return "{\n"
+ " \"comment_id\": \"\",\n"
+ " \"comment_create_time\": 0\n"
Expand All @@ -165,4 +169,10 @@ private String errorMassage(String error){
+ " \"message\": \"성공\"\n"
+ "}";
}

private Long getAccessTokenOfMemberId(HttpServletRequest request) {
String token = jwtProvider.getAccessToken(request);
Long member_id = Long.valueOf(jwtProvider.getIdFromToken(token)); //토큰
return member_id;
}
}
8 changes: 4 additions & 4 deletions src/main/java/com/example/just/Controller/PostController.java
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,6 @@ public ResponseEntity<Object> getPosts(@RequestParam Long request_page,
@Operation(summary = "자기의 게시글을 조회하는 API", description = "<big> 자신의 게시글을 조회한다</big>")
@GetMapping("/get/mypost")
public ResponseEntity<Object> getMyPosts(HttpServletRequest request) throws NotFoundException {

Long member_id = getAccessTokenOfMemberId(request);
try {
return ResponseEntity.ok(postService.getMyPost(member_id));
Expand All @@ -61,7 +60,6 @@ public ResponseEntity<Object> getMyPosts(HttpServletRequest request) throws NotF
public ResponseEntity<Object> getMemberPosts(@RequestParam Long request_page, HttpServletRequest request) {
String cursor = request.getHeader("viewed");
Long member_id = getAccessTokenOfMemberId(request);
String like = request.getHeader("like");
try {
return ResponseEntity.ok(postService.searchByCursorMember(cursor, request_page, member_id));
} catch (NotFoundException e) {
Expand Down Expand Up @@ -92,9 +90,11 @@ public PostPostDto write(HttpServletRequest request,
@Operation(summary = "게시글 삭제 api", description = "\n 글이 삭제되면 value : 삭제 완료"
+ "\n 글이 없으면 value : 글이 없습니다.")
@DeleteMapping("/delete/post")
public ResponseEntity<String> deletePost(@RequestParam Long post_id) throws NotFoundException {
public ResponseEntity<String> deletePost(@RequestParam Long post_id, HttpServletRequest request)
throws NotFoundException {
Long member_id = getAccessTokenOfMemberId(request);
try {
postService.deletePost(post_id);
postService.deletePost(post_id, member_id);
return ResponseEntity.ok("삭제 완료");
} catch (NotFoundException e) {
return ResponseEntity.notFound().build();
Expand Down
33 changes: 33 additions & 0 deletions src/main/java/com/example/just/Dao/PostLike.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
package com.example.just.Dao;

import javax.persistence.*;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;

@Entity
@Table(name = "post_like")
@Getter
@Setter
@NoArgsConstructor
public class PostLike {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

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

@ManyToOne
@JoinColumn(name = "member_id")
private Member member;

public PostLike(Post post, Member member) {
this.post = post;
this.member = member;

}

}
13 changes: 13 additions & 0 deletions src/main/java/com/example/just/Repository/PostLikeRepository.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
package com.example.just.Repository;

import com.example.just.Dao.Member;
import com.example.just.Dao.Post;
import com.example.just.Dao.PostLike;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;

public interface PostLikeRepository extends JpaRepository<PostLike, Long> {
PostLike findByPostAndMember(Post post, Member member);

List<PostLike> findByMember(Member member);
}
Original file line number Diff line number Diff line change
Expand Up @@ -48,19 +48,14 @@ public ResponseGetMemberPostDto(Post post, Long member_id, Member member) {
this.post_like_size = post.getPost_like();
this.blamed_count = Math.toIntExact(post.getBlamedCount());
this.like = false;
for (int i = 0; i < post.getLikedMembers().size(); i++) {
System.out.println(post.getLikedMembers().get(i).getId());
if (post.getLikedMembers().get(i).getId() == member_id) {

this.like = true;
break;
}
if (member.getLikedPosts().contains(post)) {
this.like = true;
}
}


public ResponseGetMemberPostDto(List<Post> results, Long member_id, int i, List<HashTagMap> hashTagMaps) {

public ResponseGetMemberPostDto(List<Post> results, Long member_id, int i, List<HashTagMap> hashTagMaps,
Member member) {
this.post_id = results.get(i).getPost_id();
this.post_content = results.get(i).getPostContent();
this.post_picture = results.get(i).getPost_picture();
Expand All @@ -81,6 +76,10 @@ public ResponseGetMemberPostDto(List<Post> results, Long member_id, int i, List<
this.mine = false;
}
}

if (member.getLikedPosts().stream().anyMatch(post -> post.getPost_id().equals(results.get(i).getPost_id()))) {
this.like = true;
} else {
this.like = false;
}
}
}
45 changes: 28 additions & 17 deletions src/main/java/com/example/just/Service/CommentService.java
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ public Comment createComment(Long postId, Long member_id, CommentDto commentDto)
if (commentDto.getParent_comment_id() != null && commentDto.getParent_comment_id() != 0) {
parentComment = commentRepository.findById(commentDto.getParent_comment_id())
.orElseThrow(() -> new NullPointerException("부모 댓글이 존재하지 않습니다."));
if(parentComment.getParent() != null){
if (parentComment.getParent() != null) {
throw new RuntimeException("해당 댓글에는 대댓글을 작성할 수 없습니다.");
}
}
Expand Down Expand Up @@ -113,7 +113,7 @@ public ResponsePostCommentDto getCommentList(Long postId, HttpServletRequest req
if (post != null && post.getComments() != null) {
comments = post.getComments().stream()
.filter(comment -> comment.getParent() == null)
.map(comment -> new ResponseCommentDto(comment, member_id,""))
.map(comment -> new ResponseCommentDto(comment, member_id, ""))
.collect(Collectors.toList());
}

Expand All @@ -137,32 +137,43 @@ public ResponsePostCommentDtoBefore getCommentListBefore(Long postId, HttpServle
return new ResponsePostCommentDtoBefore(post.getPostContent(), comments);
}

public ResponseEntity<String> deleteComment(Long postId, Long commentId) {
public ResponseEntity<String> deleteComment(Long postId, Long commentId, Long member_id) {
Post post = postRepository.findById(postId)
.orElseThrow(() -> new RuntimeException("게시물이 존재하지 않습니다."));
Comment comment = commentRepository.findById(commentId)
.orElseThrow(() -> new RuntimeException("부모 댓글이 존재하지 않습니다."));
comment.setChildren(null);
PostDocument postDocument = postContentESRespository.findById(postId).get();
postDocument.setCommentSize(postDocument.getCommentSize() - 1);
postContentESRespository.save(postDocument);
commentRepository.deleteById(commentId);
return ResponseEntity.ok("ok");
if (comment.getMember().getId() == member_id) {
comment.setChildren(null);
PostDocument postDocument = postContentESRespository.findById(postId).get();
postDocument.setCommentSize(postDocument.getCommentSize() - 1);
postContentESRespository.save(postDocument);
commentRepository.deleteById(commentId);
return ResponseEntity.ok("ok");
} else {
return ResponseEntity.status(403).body("권한이 없습니다.");
}
}

public ResponseEntity<String> putComment(Long postId, Long commentId,
PutCommentDto commentDto) {
PutCommentDto commentDto, Long member_id) {
Comment comment = commentRepository.findById(commentId).get();
if(comment == null) ResponseEntity.status(404).body("댓글이 존재하지 않습니다.");
if (comment == null) {
ResponseEntity.status(404).body("댓글이 존재하지 않습니다.");
}

Post post = postRepository.findById(postId).get();
if(post == null) ResponseEntity.status(404).body("게시물이 존재하지 않습니다.");

comment.setComment_content(commentDto.getComment_content());
// 업데이트된 댓글을 저장합니다.
commentRepository.save(comment);
if (post == null) {
ResponseEntity.status(404).body("게시물이 존재하지 않습니다.");
}
if (comment.getMember().getId() == member_id) {
comment.setComment_content(commentDto.getComment_content());
// 업데이트된 댓글을 저장합니다.
commentRepository.save(comment);

return ResponseEntity.ok(comment.getComment_content());
return ResponseEntity.ok(comment.getComment_content());
} else {
return ResponseEntity.status(403).body("권한이 없습니다.");
}
}

public ResponseEntity<String> blameComment(Long postId, Long commentId) {
Expand Down
Loading

0 comments on commit c9672ba

Please sign in to comment.