The second slice of the wishlist is the API, in server/app.js. Each product has one wishlist address, like /api/wishlist/6, and the method says what to do with it: PUT saves it, DELETE removes it. GET /api/wishlist lists what the visitor saved.
PUT means "make it so": sending it twice leaves the same result. The table allows one row per pair, so the save uses INSERT OR IGNORE, which skips a row that is already there. The answer is 204 No Content: done, nothing to send back. A newsletter sign-up could work the same way:
app.put("/api/newsletter", requireLogin, (req, res) => {
db.prepare("INSERT OR IGNORE INTO subscribers (user_id) VALUES (?)").run(req.user.id);
res.status(204).end();
});
All three routes use requireLogin, so a guest gets 401. A visitor reads and removes only their own rows, and a PUT for a product that doesn't exist answers 404.
The check opens the page, then sends these requests. Ana is user 1; after her login, her session cookie goes with each request:
GET /api/wishlist → 401 {"error": "Login required"}
PUT /api/wishlist/6 → 401 {"error": "Login required"}
POST /api/login → 200 {"email": "ana@example.com", "id": 1}
GET /api/wishlist → 200 []
PUT /api/wishlist/6 → 204 (empty)
PUT /api/wishlist/6 → 204 (empty)
PUT /api/wishlist/1 → 204 (empty)
GET /api/wishlist → 200 [{"id": 1, "name": "Mug", "price": 12, "stock": 10}, {"id": 6, "name": "Teapot", "price": 22, "stock": 4}]
DELETE /api/wishlist/6 → 204 (empty)
GET /api/wishlist → 200 [{"id": 1, "name": "Mug", "price": 12, "stock": 10}]
PUT /api/wishlist/99 → 404 {"error": "Product not found"}
Your task: in server/app.js, below the cart routes, add GET /api/wishlist, PUT /api/wishlist/:productId and DELETE /api/wishlist/:productId.
Assignment
Follow the Coding Tutorial to write the wishlist's three routes in server/app.js: the list, the save with its 404 check, and the removal.
HintrequireLogin goes between the path and the handler. In the DELETE, put both user_id and product_id in the WHERE, so a visitor removes only their own row.
Free plan: 30 tutor messages. PRO is unlimited.
