blob: 17dabb3281e1ae56f5fd964908b988297c4bbdf3 [file] [log] [blame]
2230110243e9dfe2025-05-17 16:27:12 +08001package com.pt.controller;
2
3import com.pt.constant.Constants;
4import com.pt.service.CommentService;
5import com.pt.utils.JWTUtils;
6import com.pt.entity.Comment;
7import org.springframework.beans.factory.annotation.Autowired;
8import org.springframework.http.ResponseEntity;
9import org.springframework.web.bind.annotation.*;
10
11import java.util.HashMap;
12import java.util.List;
13import java.util.Map;
14
15@RestController
16@RequestMapping("/api/comment")
17@CrossOrigin(origins = "*")
18public 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");
22301102aadb0ac2025-06-05 18:02:21 +080075 ans.put("data", Map.of(
76 "comments", comments
77 ));
2230110243e9dfe2025-05-17 16:27:12 +080078 return ResponseEntity.ok(ans);
79 }
80}