package com.guams.review.controller; import com.guams.review.exception.NotFoundException; import com.guams.review.modele.dao.Post; import com.guams.review.service.PostService; import lombok.RequiredArgsConstructor; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.util.Assert; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; import java.io.IOException; import java.time.LocalDate; import java.util.List; @RequiredArgsConstructor @RestController @RequestMapping("/api/posts") public class PostController { private final PostService postService; @GetMapping public List listPosts() { return postService.list(); } @GetMapping("/{id}") public Post findPost(@PathVariable Long id) { return postService.findById(id).orElseThrow(() -> new NotFoundException("Post not found")); } @PutMapping("/{id}") public void updatePost(@PathVariable Long id, @RequestBody Post updatedPost) { Post postToUpdate = postService.findById(id).orElseThrow(() -> new NotFoundException("Post not found")); postService.insert(updatedPost .setId(postToUpdate.getId()) .setIllustration(postToUpdate.getIllustration()) .setPublicationDate(postToUpdate.getPublicationDate())); } @PutMapping(value = "{id}/illustration", consumes = {MediaType.MULTIPART_FORM_DATA_VALUE}) public void updateIllustration(@PathVariable Long id, @RequestPart MultipartFile illustration) throws IOException { Post postToUpdate = postService.findById(id).orElseThrow(() -> new NotFoundException("Post not found")); postService.insert(postToUpdate.setIllustration(illustration.getBytes())); } @PostMapping public ResponseEntity addPost(@RequestBody Post postToCreate) { Assert.isNull(postToCreate.getId(), "Post id must be null"); return new ResponseEntity<>(postService.insert(postToCreate.setPublicationDate(LocalDate.now())), HttpStatus.CREATED); } @DeleteMapping("{id}") public void deletePost(@PathVariable Long id) { Post postToDelete = postService.findById(id).orElseThrow(() -> new NotFoundException("Post not found")); postService.delete(postToDelete.getId()); } }