Start learning free

LESSON 25 OF 58 · FULL-STACK: CART AND CHECKOUT

The Cart on the Server in JavaScript

Practice

A shopping cart must outlive the page. If it lives only in the browser, a reload or a second device loses it. So the shop keeps it on the server, in the cart_items table of shop.db: one row per user and product, with a quantity.

Every cart route answers the whole cart: {items: [{product_id, name, price, quantity}], total}. The page never adds up prices itself: it shows what the server sends. The given helper cartOf(userId) builds that answer from the table, and requireLogin puts the logged-in user in req.user (or answers 401). The given /api/me route shows how a route uses it:

app.get("/api/me", requireLogin, (req, res) => {
  res.json(req.user);
});

Adding to the cart has two checks. A product id that is not in products gets 404. And the line's new quantity is its old quantity (0 when there is no line) plus the one asked for: if that is more than the product's stock, the answer is 409 Conflict, like {"error": "Only 1 left"}.

The check logs in as Ana, clicks "Add to cart" on the Mug twice and on the Lamp twice, and opens her cart. Then it sends plain requests, first without logging in, then as Ben:

POST /api/cart {"product_id": 1, "quantity": 1}  →  200  page: Cart total: $12
POST /api/cart {"product_id": 1, "quantity": 1}  →  200  page: Cart total: $24
POST /api/cart {"product_id": 3, "quantity": 1}  →  200  page: Cart total: $53
POST /api/cart {"product_id": 3, "quantity": 1}  →  409  page: Only 1 left
GET /api/cart  →  200  page: Mug × 2 $24, Lamp × 1 $29, Total: $53

GET /api/cart  (not logged in)                    →  401  {"error": "Login required"}
POST /api/cart {"product_id": 99, "quantity": 1} →  404  {"error": "No such product"}
POST /api/cart {"product_id": 6, "quantity": 5}  →  409  {"error": "Only 4 left"}
GET /api/cart  (as Ben)                           →  200  {"items": [], "total": 0}

Your task: in server/app.js, add GET /api/cart and POST /api/cart, both behind requireLogin and both answering cartOf(req.user.id). In the POST route, answer 404 {"error": "No such product"} for an unknown product and 409 with "Only " + stock + " left" beyond the stock; otherwise save the line with INSERT OR REPLACE.


Assignment
Follow the Coding Tutorial to write the two cart routes in server/app.js: the GET that answers the cart, and the POST that checks the product and the stock, then saves the line.


Hint
The table's key is (user_id, product_id), so INSERT OR REPLACE overwrites a line that is already there. Work out the new quantity before the stock check: when the product is not in the cart yet, its old quantity is 0.


STEP 1 OF 12
    Ctrl + Enter to check

    Fscart Routes in JavaScript

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