Start learning free

LESSON 58 OF 58 · FULL-STACK: SHIP A FEATURE

Review the AI's Patch

Practice

Reviewing a patch means asking what the code does for every request, not just the ones the page sends. The page is one client among many: anyone logged in can send the same request with curl or a script. So a route must check for itself what the page only hides.

An AI teammate added "Move to cart" to the wishlist page, with the route POST /api/users/:userId/wishlist/:productId/move. It has two holes. The route trusts the user id in the address, so Ben can move Ana's items. And only the page looks at the stock: it disables the button at stock 0, but the route moves a Lamp even when the cart already holds the last one.

Here is the same kind of check on another route, an order that must belong to the visitor:

app.get("/api/orders/:orderId", requireLogin, (req, res) => {
  const order = db.prepare("SELECT * FROM orders WHERE id = ?").get(req.params.orderId);
  if (order === undefined || order.user_id !== req.user.id) {
    return res.status(404).json({ error: "Order not found" });
  }
  res.json(order);
});

A 404 tells a stranger nothing, not even that the thing exists. A 409 Conflict says the request is fine but the shop's state says no, like POST /api/cart when the stock runs out. After your fix, the page still works and the check's direct requests are refused:

Ana clicks "Move to cart" in "Mug"   →  POST /api/users/1/wishlist/1/move  →  200
Ana clicks "Move to cart" in "Lamp"  →  POST /api/users/1/wishlist/3/move  →  409
    alert: Only 1 Lamp left
Ben: POST /api/users/1/wishlist/6/move  →  404  {"error": "Not found"}
Ben: PUT /api/wishlist/2                →  204
Ben: POST /api/users/2/wishlist/2/move  →  409  {"error": "Only 0 Notebook left"}

Your task: in the move route of server/app.js, answer 404 with "Not found" when the address's user id, as a number, is not the logged-in user's id. Then answer 409 with the same error as POST /api/cart when the new quantity is more than the product's stock.


Assignment
Follow the Coding Tutorial to add the two checks the AI's route is missing: whose wishlist it is, and how many are left.


Hint
req.params.userId is a string; Number(…) turns it into a number before you compare it with req.user.id. The stock check goes right below the quantity line, before anything is written to the database.


STEP 1 OF 4
    Ctrl + Enter to check