CartController.java 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. package com.example.plantsforyou.cart;
  2. import com.example.plantsforyou.appuser.AppUser;
  3. import com.example.plantsforyou.appuser.AppUserService;
  4. import com.example.plantsforyou.dto.AddToCartDto;
  5. import com.example.plantsforyou.exceptions.RejectedRequestException;
  6. import com.example.plantsforyou.plant.Plant;
  7. import com.example.plantsforyou.plant.PlantService;
  8. import org.springframework.beans.factory.annotation.Autowired;
  9. import org.springframework.http.HttpStatus;
  10. import org.springframework.http.ResponseEntity;
  11. import org.springframework.stereotype.Controller;
  12. import org.springframework.web.bind.annotation.*;
  13. import org.springframework.web.context.request.RequestContextHolder;
  14. import org.springframework.web.context.request.ServletRequestAttributes;
  15. import java.util.Optional;
  16. @RestController
  17. @RequestMapping("api/v1/cart")
  18. public class CartController {
  19. private final CartService cartService;
  20. private final PlantService plantService;
  21. private final AppUserService appUserService;
  22. @Autowired
  23. public CartController(CartService cartService, PlantService plantService, AppUserService appUserService) {
  24. this.cartService = cartService;
  25. this.plantService = plantService;
  26. this.appUserService = appUserService;
  27. }
  28. @PostMapping
  29. public ResponseEntity<Object> addToCart(@RequestBody AddToCartDto addToCartDto) throws RejectedRequestException {
  30. String token = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest().getHeader("Authorization").substring("Bearer: ".length());
  31. AppUser appUser = appUserService.getUserFromToken(token);
  32. Plant plant = plantService.findPlantById(addToCartDto.getPlantId());
  33. cartService.addToCart(addToCartDto, plant, appUser);
  34. return new ResponseEntity<>(HttpStatus.CREATED);
  35. }
  36. }