source: backend/src/main/java/com/finki/icare/service/CommentService.java

main
Last change on this file was 700e2f9, checked in by 186079 <matej.milevski@…>, 5 days ago

Init

  • Property mode set to 100644
File size: 2.8 KB
Line 
1package com.finki.icare.service;
2
3import com.finki.icare.dto.CommentDTO;
4import com.finki.icare.dto.CreateCommentRequest;
5import com.finki.icare.exceptions.ICareException;
6import com.finki.icare.mapper.CommentMapper;
7import com.finki.icare.model.Blog;
8import com.finki.icare.model.Comment;
9import com.finki.icare.model.Patient;
10import com.finki.icare.repository.BlogRepository;
11import com.finki.icare.repository.CommentRepository;
12import com.finki.icare.repository.PatientRepository;
13import lombok.RequiredArgsConstructor;
14import org.springframework.stereotype.Service;
15import org.springframework.transaction.annotation.Transactional;
16
17import java.time.OffsetDateTime;
18
19@Service
20@RequiredArgsConstructor
21public class CommentService {
22
23 private final CommentRepository commentRepository;
24 private final BlogRepository blogRepository;
25 private final PatientRepository patientRepository;
26 private final CommentMapper commentMapper;
27
28 @Transactional
29 public CommentDTO createComment(Integer blogId, CreateCommentRequest request, Integer patientId) {
30 Blog blog = blogRepository
31 .findById(blogId)
32 .orElseThrow(() -> ICareException.notFound("Blog not found with id: " + blogId));
33
34 Patient patient = patientRepository
35 .findById(patientId)
36 .orElseThrow(() -> ICareException.unauthorized("Only patients can comment"));
37
38 Comment comment = new Comment();
39 comment.setBlog(blog);
40 comment.setPatient(patient);
41 comment.setContent(request.getContent());
42 comment.setDateOfComment(OffsetDateTime.now());
43
44 Comment savedComment = commentRepository.save(comment);
45 return commentMapper.toDTO(savedComment);
46 }
47
48 @Transactional
49 public CommentDTO updateComment(Integer commentId, String content, Integer patientId) {
50 Comment comment = commentRepository
51 .findById(commentId)
52 .orElseThrow(() -> ICareException.notFound("Comment not found with id: " + commentId));
53
54 if (!comment.getPatient().getIdUser().equals(patientId)) {
55 throw ICareException.forbidden("You are not authorized to update this comment");
56 }
57
58 comment.setContent(content);
59 Comment updatedComment = commentRepository.save(comment);
60 return commentMapper.toDTO(updatedComment);
61 }
62
63 @Transactional
64 public void deleteComment(Integer commentId, Integer patientId) {
65 Comment comment = commentRepository
66 .findById(commentId)
67 .orElseThrow(() -> ICareException.notFound("Comment not found with id: " + commentId));
68
69 if (!comment.getPatient().getIdUser().equals(patientId)) {
70 throw ICareException.forbidden("You are not authorized to delete this comment");
71 }
72
73 commentRepository.delete(comment);
74 }
75}
Note: See TracBrowser for help on using the repository browser.