From 9a00e7eb163a887913f657168a73bf6a875b9d43 Mon Sep 17 00:00:00 2001 From: Johannes Kantz <67144859+JohannesKantz@users.noreply.github.com> Date: Tue, 24 Jan 2023 04:05:15 +0100 Subject: [PATCH] add: update and delete ingredients --- index.php | 36 +++++++++++++++++++++++++++++++----- 1 file changed, 31 insertions(+), 5 deletions(-) diff --git a/index.php b/index.php index f5aee5d..b946653 100644 --- a/index.php +++ b/index.php @@ -113,11 +113,37 @@ $app->route("/ingredient") $res->json(["message" => "New ingredient has been listed", "ingredient" => $db->select("ingredienti", ["id" => $id])]); }); -$app->get("/ingredient/:id", function (array $req, Response $res) use ($db) { - $id = $req["params"]["id"]; - $ingredient = $db->select("ingredienti", ["id" => $id])[0]; - $res->json(["data" => $ingredient]); -}); +$app->route("/ingredient/:id") + ->get(function (array $req, Response $res) use ($db) { + $id = $req["params"]["id"]; + $ingredient = $db->select("ingredienti", ["id" => $id])[0]; + $res->json(["data" => $ingredient]); + }) + ->put(function (array $req, Response $res) use ($db) { + $id = $req["params"]["id"]; + + $name = $req["body"]["name"]; + $calories = $req["body"]["calories"]; + $quantity = $req["body"]["quantity"]; + $unit = $req["body"]["unit"]; + $price = $req["body"]["price"]; + + $unitInTable = $db->select("folla", ["unita" => $unit]); + if (count($unitInTable) > 1) { + $res->json(["message" => "Unit: " . $unit . " does not exist. Please create unit first"], HTTP_STATUS_CODE::BAD_REQUEST); + return; + } + $unitId = $unitInTable[0]["id"]; + + $db->update("ingredienti", $id,["cognome" => "$name", "calorie" => "$calories", "quantita" => "$quantity", "follaID" => $unitId, "prezzo" => "$price"]); + + $res->json(["message" => "Ingredient has been updated", "data" => $db->select("ingredienti", ["id" => $id])[0]]); + }) + ->delete(function (array $req, Response $res) use ($db) { + $id = $req["params"]["id"]; + $db->delete("ingredienti", $id); + $res->json(["message" => "Ingredient has been deleted"]); + }); /* * Unit