22301102 | 43e9dfe | 2025-05-17 16:27:12 +0800 | [diff] [blame] | 1 | package com.pt.controller; |
| 2 | |
| 3 | import com.pt.constant.Constants; |
| 4 | import com.pt.service.CommentService; |
| 5 | import com.pt.utils.JWTUtils; |
| 6 | import com.pt.entity.Comment; |
| 7 | import org.springframework.beans.factory.annotation.Autowired; |
| 8 | import org.springframework.http.ResponseEntity; |
| 9 | import org.springframework.web.bind.annotation.*; |
| 10 | |
| 11 | import java.util.HashMap; |
| 12 | import java.util.List; |
| 13 | import java.util.Map; |
| 14 | |
| 15 | @RestController |
| 16 | @RequestMapping("/api/comment") |
| 17 | @CrossOrigin(origins = "*") |
| 18 | public class CommentController { |
| 19 | |
| 20 | @Autowired |
| 21 | private CommentService commentService; |
| 22 | |
| 23 | @PostMapping("/add") |
| 24 | public ResponseEntity<?> addComment( |
| 25 | @RequestHeader("token") String token, |
| 26 | @RequestParam("content") String content, |
| 27 | @RequestParam("username") String username, |
| 28 | @RequestParam("postId") int postId |
| 29 | ) { |
| 30 | Map<String, Object> ans = new HashMap<>(); |
| 31 | |
| 32 | if (!JWTUtils.checkToken(token, username, Constants.UserRole.USER)) { |
| 33 | ans.put("result", "Invalid token"); |
| 34 | return ResponseEntity.badRequest().body(ans); |
| 35 | } |
| 36 | |
| 37 | commentService.addComment(content, username, postId); |
| 38 | ans.put("result", "Comment added successfully"); |
| 39 | return ResponseEntity.ok(ans); |
| 40 | } |
| 41 | |
| 42 | @DeleteMapping("/delete") |
| 43 | public ResponseEntity<?> deleteComment( |
| 44 | @RequestHeader("token") String token, |
| 45 | @RequestParam("commentId") int commentId, |
| 46 | @RequestParam("username") String username |
| 47 | ) { |
| 48 | Map<String, Object> ans = new HashMap<>(); |
| 49 | |
| 50 | if (!JWTUtils.checkToken(token, username, Constants.UserRole.ADMIN)) { |
| 51 | ans.put("result", "Invalid token"); |
| 52 | return ResponseEntity.badRequest().body(ans); |
| 53 | } |
| 54 | |
| 55 | commentService.deleteComment(commentId); |
| 56 | ans.put("result", "Comment deleted successfully"); |
| 57 | return ResponseEntity.ok(ans); |
| 58 | } |
| 59 | |
| 60 | @GetMapping("/get") |
| 61 | public ResponseEntity<?> getComments( |
| 62 | @RequestHeader("token") String token, |
| 63 | @RequestParam("postId") int postId, |
| 64 | @RequestParam("username") String username |
| 65 | ) { |
| 66 | Map<String, Object> ans = new HashMap<>(); |
| 67 | |
| 68 | if(!JWTUtils.checkToken(token, username, Constants.UserRole.USER)) { |
| 69 | ans.put("result", "Invalid token"); |
| 70 | return ResponseEntity.badRequest().body(ans); |
| 71 | } |
| 72 | |
| 73 | List<Comment> comments = commentService.getCommentsByPostId(postId); |
| 74 | ans.put("result", "Comments retrieved successfully"); |
| 75 | ans.put("comments", comments); |
| 76 | return ResponseEntity.ok(ans); |
| 77 | } |
| 78 | } |