With PUT, a client sends the whole product, even to change one number: name, price and category, including the ones that stay the same. PATCH is the method for a partial change. Its body holds only the keys to change, like {"price": 5}, and every other key keeps its value.
So the method copies a key only when the body has it. A map's containsKey tells you whether it has a key:
Map<String, Object> data = Map.of("price", 5);
System.out.println(data.containsKey("price")); // true
System.out.println(data.containsKey("name")); // false
A client may change a product's name, price and category, but never its id: other requests find the product by it. So your method goes over a fixed list of those three keys and copies each one only if the body has it. An "id" in the body is never copied. The requests and answers your code must give, in this order:
PATCH /products/2 {"price": 5}
→ 200 {"id": 2, "name": "Notebook", "price": 5, "category": "office"}
GET /products/2 → 200 {"id": 2, "name": "Notebook", "price": 5, "category": "office"}
PATCH /products/3 {"name": "Desk lamp", "category": "office"}
→ 200 {"id": 3, "name": "Desk lamp", "price": 29, "category": "office"}
PATCH /products/1 {"id": 7, "price": 14}
→ 200 {"id": 1, "name": "Mug", "price": 14, "category": "kitchen"}
PATCH /products/4 {}
→ 200 {"id": 4, "name": "Pen", "price": 2, "category": "office"}
PATCH /products/99 {"price": 5}
→ 404 {"error": "Product not found"}
PUT /products/4 {"name": "Blue pen", "price": 3, "category": "office"}
→ 200 {"id": 4, "name": "Blue pen", "price": 3, "category": "office"}
GET /products → 200 [{"id": 1, "name": "Mug", "price": 14, …}, {"id": 2, "name": "Notebook", "price": 5, …}, {"id": 3, "name": "Desk lamp", …}, {"id": 4, "name": "Blue pen", …}]
Your task: add PATCH /products/{productId}. Its method patchProduct finds the product with that id, copies each of "name", "price" and "category" from the body only if the body has it, and returns the whole product. When no product has that id, it answers 404 with {"error": "Product not found"}.
Assignment
Follow the Coding Tutorial to add the PATCH route that changes only the keys the client sends.
Hint
The first lines are the same as in updateProduct. Inside the if, loop over the three keys and check data.containsKey(key) before copying. Watch the braces: return product; goes after the loop over the keys, still inside the if.
Free plan: 30 tutor messages. PRO is unlimited.
