blob: 00e091dbc1c45e2414b313532a8cece5c7100c50 [file] [log] [blame]
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,
@RequestBody Map<String, String> request
) {
String content = request.get("content");
String username = request.get("username");
int postId = Integer.parseInt(request.get("postId"));
Map<String, Object> ans = new HashMap<>();
if (!JWTUtils.checkToken(token, username, Constants.UserRole.USER)) {
ans.put("message", "Invalid token");
return ResponseEntity.badRequest().body(ans);
}
commentService.addComment(content, username, postId);
ans.put("message", "Comment added successfully");
return ResponseEntity.ok(ans);
}
@DeleteMapping("/delete")
public ResponseEntity<?> deleteComment(
@RequestHeader("token") String token,
@RequestBody Map<String, String> request
) {
String username = request.get("username");
int commentId = Integer.parseInt(request.get("commentId"));
Map<String, Object> ans = new HashMap<>();
if (!JWTUtils.checkToken(token, username, Constants.UserRole.ADMIN)) {
ans.put("message", "Invalid token");
return ResponseEntity.badRequest().body(ans);
}
commentService.deleteComment(commentId);
ans.put("message", "Comment deleted successfully");
return ResponseEntity.ok(ans);
}
@GetMapping("/get")
public ResponseEntity<?> getComments(
@RequestHeader("token") String token,
@RequestParam("username") String username,
@RequestParam("postId") int postId
) {
Map<String, Object> ans = new HashMap<>();
if(!JWTUtils.checkToken(token, username, Constants.UserRole.USER)) {
ans.put("message", "Invalid token");
return ResponseEntity.badRequest().body(ans);
}
List<Comment> comments = commentService.getCommentsByPostId(postId);
ans.put("message", "Comments retrieved successfully");
ans.put("data", Map.of(
"comments", comments
));
return ResponseEntity.ok(ans);
}
}