完成评论的基本的功能
Change-Id: I798126b0411b49b67111420247cb9884f1b41411
diff --git a/src/main/java/com/pt/controller/CommentController.java b/src/main/java/com/pt/controller/CommentController.java
new file mode 100644
index 0000000..a85d131
--- /dev/null
+++ b/src/main/java/com/pt/controller/CommentController.java
@@ -0,0 +1,78 @@
+package com.pt.controller;
+
+import com.pt.constant.Constants;
+import com.pt.service.CommentService;
+import com.pt.utils.JWTUtils;
+import com.pt.entity.Comment;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.http.ResponseEntity;
+import org.springframework.web.bind.annotation.*;
+
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+@RestController
+@RequestMapping("/api/comment")
+@CrossOrigin(origins = "*")
+public class CommentController {
+
+ @Autowired
+ private CommentService commentService;
+
+ @PostMapping("/add")
+ public ResponseEntity<?> addComment(
+ @RequestHeader("token") String token,
+ @RequestParam("content") String content,
+ @RequestParam("username") String username,
+ @RequestParam("postId") int postId
+ ) {
+ Map<String, Object> ans = new HashMap<>();
+
+ if (!JWTUtils.checkToken(token, username, Constants.UserRole.USER)) {
+ ans.put("result", "Invalid token");
+ return ResponseEntity.badRequest().body(ans);
+ }
+
+ commentService.addComment(content, username, postId);
+ ans.put("result", "Comment added successfully");
+ return ResponseEntity.ok(ans);
+ }
+
+ @DeleteMapping("/delete")
+ public ResponseEntity<?> deleteComment(
+ @RequestHeader("token") String token,
+ @RequestParam("commentId") int commentId,
+ @RequestParam("username") String username
+ ) {
+ Map<String, Object> ans = new HashMap<>();
+
+ if (!JWTUtils.checkToken(token, username, Constants.UserRole.ADMIN)) {
+ ans.put("result", "Invalid token");
+ return ResponseEntity.badRequest().body(ans);
+ }
+
+ commentService.deleteComment(commentId);
+ ans.put("result", "Comment deleted successfully");
+ return ResponseEntity.ok(ans);
+ }
+
+ @GetMapping("/get")
+ public ResponseEntity<?> getComments(
+ @RequestHeader("token") String token,
+ @RequestParam("postId") int postId,
+ @RequestParam("username") String username
+ ) {
+ Map<String, Object> ans = new HashMap<>();
+
+ if(!JWTUtils.checkToken(token, username, Constants.UserRole.USER)) {
+ ans.put("result", "Invalid token");
+ return ResponseEntity.badRequest().body(ans);
+ }
+
+ List<Comment> comments = commentService.getCommentsByPostId(postId);
+ ans.put("result", "Comments retrieved successfully");
+ ans.put("comments", comments);
+ return ResponseEntity.ok(ans);
+ }
+}