diff --git a/service/routes.py b/service/routes.py index c7185e0..4d6b360 100644 --- a/service/routes.py +++ b/service/routes.py @@ -251,6 +251,39 @@ def get_shopcart_items(shopcart_id, item_id): return jsonify(item.serialize()), status.HTTP_200_OK +###################################################################### +# RETRIEVE AN ITEM FROM SHOPCART BY PRODUCT ID +###################################################################### +@app.route("/shopcarts//items/", methods=["GET"]) +def get_shopcart_items_by_product_id(shopcart_id, product_id): + """ + Get an Item + + This endpoint returns just an item using the product id + """ + app.logger.info( + "Request to retrieve Item %s for ShopCart id: %s", (product_id, shopcart_id) + ) + + # Search for the shopcart + shopcart = ShopCart.find(shopcart_id) + if not shopcart: + abort( + status.HTTP_404_NOT_FOUND, + f"ShopCart with ID '{shopcart_id}' could not be found", + ) + + # See if the item exists and abort if it doesn't + item = ShopCartItem.find_by_product_id(product_id) + if not item: + abort( + status.HTTP_404_NOT_FOUND, + f"Product with id '{product_id}' could not be found.", + ) + + return jsonify(item.serialize()), status.HTTP_200_OK + + ###################################################################### # DELETE AN ITEM FROM SHOPCART ###################################################################### diff --git a/tests/test_routes.py b/tests/test_routes.py index 0e31e00..3f21b29 100644 --- a/tests/test_routes.py +++ b/tests/test_routes.py @@ -342,6 +342,37 @@ def test_get_shopcart_item_when_no_shopcart(self): ) self.assertEqual(resp.status_code, status.HTTP_404_NOT_FOUND) + def test_get_shopcart_item_by_product_id(self): + """It should Get an item from a shopcart by product id""" + # create a known item + shopcart = self._create_shopcarts(1)[0] + item = ShopCartItemFactory() + resp = self.client.post( + f"{BASE_URL}/{shopcart.id}/items", + json=item.serialize(), + content_type="application/json", + ) + self.assertEqual(resp.status_code, status.HTTP_201_CREATED) + + data = resp.get_json() + logging.debug(data) + product_id = data["product_id"] + + # retrieve it back + resp = self.client.get( + f"{BASE_URL}/{shopcart.id}/items/{product_id}", + content_type="application/json", + ) + self.assertEqual(resp.status_code, status.HTTP_200_OK) + + data = resp.get_json() + logging.debug(data) + self.assertEqual(data["shop_cart_id"], shopcart.id) + self.assertEqual(data["name"], item.name) + self.assertEqual(data["product_id"], item.product_id) + self.assertEqual(data["quantity"], item.quantity) + self.assertEqual(data["price"], str(item.price)) + def test_delete_shopcart_item(self): """It should delete a shopcart item""" shopcart = self._create_shopcarts(1)[0]