Skip to content

Commit

Permalink
✨ enable the change of quantities for all Products
Browse files Browse the repository at this point in the history
  • Loading branch information
josuablejeru committed Aug 17, 2023
1 parent 84d9808 commit 65bb7fc
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 2 deletions.
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package com.josuablejeru.resupplyapi.controllers;

import com.josuablejeru.resupplyapi.controllers.errors.ProductNotFoundException;
import com.josuablejeru.resupplyapi.controllers.requestbody.ChangeProductQuantity;
import com.josuablejeru.resupplyapi.controllers.response.UpdateProductResponse;
import com.josuablejeru.resupplyapi.models.Product;
Expand All @@ -13,6 +14,7 @@
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Optional;

@RestController
@RequestMapping("/v1/products")
Expand Down Expand Up @@ -45,12 +47,17 @@ public ResponseEntity<Product> requestProduct(@RequestBody Product product) {
@PutMapping(value = "{productId}/quantity", produces = MediaType.APPLICATION_JSON_VALUE)
@ResponseBody
public UpdateProductResponse changeQuantity(@PathVariable("productId") String productId, @RequestBody ChangeProductQuantity body) {
Integer newQuantity = body.getQuantity();
Integer requestedQuantity = body.getQuantity();

Optional<Product> product = productService.getById(productId);
product.orElseThrow(() -> new ProductNotFoundException("Product not found"));

Integer newCalculatedQuantity = productService.changeQuantity(product.get(), requestedQuantity);

UpdateProductResponse response = new UpdateProductResponse();

response.setProductId(productId);
response.setQuantity(newQuantity);
response.setQuantity(newCalculatedQuantity);

return response;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

@Service
public class ProductService {
Expand All @@ -24,4 +25,17 @@ public List<Product> list() {
public Product add(Product product) {
return productRepository.save(product);
}

public Optional<Product> getById(String id) {
return productRepository.findById(id);
}

public Integer changeQuantity(Product product, Integer quantityTick) {
Integer currentQuantity = product.getQuantity();
product.setQuantity(currentQuantity + quantityTick);

productRepository.save(product);

return product.getQuantity();
}
}

0 comments on commit 65bb7fc

Please sign in to comment.