Start learning free

LESSON 24 OF 173 · BACKEND: YOUR FIRST API

Change Only the Price (PATCH) in TypeScript

Practice

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 route copies a key only when the body has it. TypeScript's in tells you whether an object has a key. And with square brackets, the name of the key can come from a variable:

const data = { price: 5 };
console.log("price" in data);   // true
console.log("name" in data);    // false

const key = "price";
console.log(data[key]);         // 5

A client may change a product's name, price and category, but never its id: other requests find the product by it. So your route goes over a fixed array 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. It finds the product with that id, copies each of name, price and category from the body only if the body has it, and answers 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 the PUT route. Inside the if, loop over the three keys and check key in data before copying. Watch the braces: the return goes after the loop over the keys, still inside the if.


STEP 1 OF 12
    Ctrl + Enter to check

    Shop Patch Price in TypeScript

    Keep going with TypeScript1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free