Start learning free

LESSON 22 OF 173 · BACKEND: YOUR FIRST API

Remove a Product in TypeScript

Practice

To remove something, a client uses the DELETE method and names what to remove in the path. DELETE /products/2 has the same path as GET /products/2, but a different method, so Express sends it to a different function.

An array's indexOf gives the position of an item (or -1 when it isn't there), and splice(index, 1) removes 1 element at that position. After a delete there is nothing to send back, so the answer is an empty body with the status 204 No Content. Here is the idea on another route:

const tags: string[] = ["new", "sale", "gift"];

app.delete("/tags/:name", (req: Request, res: Response) => {
  const index: number = tags.indexOf(req.params.name);
  if (index === -1) {
    return res.status(404).json({ error: "Tag not found" });
  }
  tags.splice(index, 1);
  res.status(204).send();
});

Your shop finds the product with a loop, like the route that reads one product, and answers 404 with the same error when no product has that id. Your code must give, in this order:

DELETE /products/2   →  204  (empty body)
GET /products/2      →  404  {"error": "Product not found"}
GET /products        →  200  [{"id": 1, …}, {"id": 3, …}, {"id": 4, …}]
DELETE /products/2   →  404  {"error": "Product not found"}
DELETE /products/99  →  404  {"error": "Product not found"}
GET /products/count  →  200  {"count": 3}
POST /products  {"name": "Plant", "price": 15, "category": "home"}  →  201  {"id": 5, "name": "Plant", "price": 15, "category": "home"}

Your task: add a DELETE /products/:productId route that removes the product with that id and answers 204 with an empty body, or 404 with {"error": "Product not found"} when there is no such product.


Assignment
Follow the Coding Tutorial to build the DELETE route for one product.


Hint
Start the function like the route that reads one product: req: Request, res: Response, next: NextFunction, and next() when the id is not a whole number. Return right after splice, inside the loop; the 404 goes after the loop, at the level of for.


STEP 1 OF 10
    Ctrl + Enter to check

    Shop Delete Product 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