Advertisement
Guest User

Untitled

a guest
Jan 23rd, 2020
123
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.64 KB | None | 0 0
  1. package com.udacity.course3.reviews.controller;
  2.  
  3. import com.udacity.course3.reviews.model.Product;
  4. import com.udacity.course3.reviews.model.Review;
  5. import com.udacity.course3.reviews.repository.ProductRepository;
  6. import com.udacity.course3.reviews.repository.ReviewRepository;
  7. import org.springframework.beans.factory.annotation.Autowired;
  8. import org.springframework.http.HttpStatus;
  9. import org.springframework.http.ResponseEntity;
  10. import org.springframework.web.bind.annotation.*;
  11. import org.springframework.web.client.HttpServerErrorException;
  12.  
  13. import java.util.Collections;
  14. import java.util.List;
  15. import java.util.Optional;
  16.  
  17. /**
  18. * Spring REST controller for working with review entity.
  19. */
  20. @RestController
  21. public class ReviewsController {
  22.  
  23.  
  24. @Autowired
  25. private ReviewRepository reviewRepository;
  26. @Autowired
  27. private ProductRepository productRepository;
  28.  
  29. /**
  30. * Creates a review for a product.
  31. * <p>
  32. * 1. Add argument for review entity. Use {@link RequestBody} annotation.
  33. * 2. Check for existence of product.
  34. * 3. If product not found, return NOT_FOUND.
  35. * 4. If found, save review.
  36. *
  37. * @param productId The id of the product.
  38. * @return The created review or 404 if product id is not found.
  39. */
  40. @RequestMapping(value = "/reviews/products/{productId}", method = RequestMethod.POST)
  41. public ResponseEntity<?> createReviewForProduct(@PathVariable("productId") Integer productId,
  42. @RequestBody Review review) {
  43.  
  44. if (productRepository.existsById(productId)) {
  45. review.setProduct(productRepository.findById(productId).get());
  46. return new ResponseEntity<Review>(reviewRepository.save(review), HttpStatus.OK); // This will return the review of a product
  47. } else {
  48. return new ResponseEntity<String>("This product Id does not exist", HttpStatus.NOT_FOUND);
  49.  
  50. }
  51. }
  52.  
  53.  
  54.  
  55. /**
  56. * Lists reviews by product.
  57. *
  58. * @param productId The id of the product.
  59. * @return The list of reviews.
  60. */
  61.  
  62. @RequestMapping(value = "/reviews/products/{productId}", method = RequestMethod.GET)
  63. public ResponseEntity<List<?>> listReviewsForProduct(@PathVariable("productId") Integer productId) {
  64. if (productRepository.existsById(productId)) {
  65. return new ResponseEntity<List<?>>(reviewRepository.findByProductId(productId), HttpStatus.OK);
  66. } // This will return the list of reviews.
  67. throw new HttpServerErrorException(HttpStatus.NOT_FOUND);
  68.  
  69. }
  70.  
  71.  
  72.  
  73. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement