|
| 1 | +package demo.rest; |
| 2 | + |
| 3 | +import java.time.LocalDateTime; |
| 4 | +import java.util.Optional; |
| 5 | + |
| 6 | +import org.springframework.http.ResponseEntity; |
| 7 | +import org.springframework.web.bind.annotation.GetMapping; |
| 8 | +import org.springframework.web.bind.annotation.PathVariable; |
| 9 | +import org.springframework.web.bind.annotation.PostMapping; |
| 10 | +import org.springframework.web.bind.annotation.PutMapping; |
| 11 | +import org.springframework.web.bind.annotation.RequestBody; |
| 12 | +import org.springframework.web.bind.annotation.RequestParam; |
| 13 | +import org.springframework.web.bind.annotation.RestController; |
| 14 | + |
| 15 | +import demo.domain.Comment; |
| 16 | +import demo.repository.CommentRepository; |
| 17 | +import lombok.RequiredArgsConstructor; |
| 18 | +import lombok.extern.slf4j.Slf4j; |
| 19 | + |
| 20 | +@RestController |
| 21 | +@Slf4j |
| 22 | +@RequiredArgsConstructor |
| 23 | +public class CommentController { |
| 24 | + |
| 25 | + private final CommentRepository commentRepository; |
| 26 | + |
| 27 | + @GetMapping("/comments") |
| 28 | + public ResponseEntity<Iterable<Comment>> getComments(@RequestParam(name = "mentionId") Integer mentionId) { |
| 29 | + return ResponseEntity.ok(commentRepository.findAllByMentionIdOrderByCreatedAtAsc(mentionId)); |
| 30 | + } |
| 31 | + |
| 32 | + @GetMapping("/comment/{id}") |
| 33 | + public ResponseEntity<Comment> getComment(@PathVariable("id") String id) { |
| 34 | + final Optional<Comment> commentOptional = commentRepository.findById(id); |
| 35 | + return commentOptional.map(ResponseEntity::ok).orElseGet(() -> ResponseEntity.notFound().build()); |
| 36 | + } |
| 37 | + |
| 38 | + @PostMapping("/comments") |
| 39 | + public ResponseEntity<Comment> createComment(@RequestBody Comment comment) { |
| 40 | + comment.setCreatedAt(LocalDateTime.now()); |
| 41 | + comment.setId(null); |
| 42 | + comment = commentRepository.save(comment); |
| 43 | + return ResponseEntity.ok(comment); |
| 44 | + } |
| 45 | + |
| 46 | + @PutMapping("/comment/{id}") |
| 47 | + public ResponseEntity<Comment> updateComment(@PathVariable("id") String id, |
| 48 | + @RequestBody Comment update) { |
| 49 | + final Optional<Comment> commentOptional = commentRepository.findById(id); |
| 50 | + |
| 51 | + if (!commentOptional.isPresent()) { |
| 52 | + return ResponseEntity.notFound().build(); |
| 53 | + } |
| 54 | + |
| 55 | + final Comment saved = commentOptional.get(); |
| 56 | + saved.setContent(update.getContent()); |
| 57 | + |
| 58 | + return ResponseEntity.ok(commentRepository.save(saved)); |
| 59 | + } |
| 60 | +} |
0 commit comments