Start learning free

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

All or Nothing in JavaScript

Practice

Checkout writes several things: the order, one line per product, and each product's new stock. If something goes wrong halfway, the first writes are already saved and the shop is left with half an order. A transaction makes them one: after db.exec("BEGIN"), SQLite keeps every change aside. db.exec("COMMIT") saves them all at once, and db.exec("ROLLBACK") throws them all away.

Here it is moving points between two accounts:

db.exec("BEGIN");
db.prepare("UPDATE accounts SET points = points - ? WHERE id = ?").run(50, fromId);
const from = db.prepare("SELECT points FROM accounts WHERE id = ?").get(fromId);
if (from.points < 0) {
  db.exec("ROLLBACK");
  return res.status(409).json({ error: "Not enough points" });
}
db.prepare("UPDATE accounts SET points = points + ? WHERE id = ?").run(50, toId);
db.exec("COMMIT");

Every way out must end the transaction. A BEGIN left open makes the next BEGIN fail with "cannot start a transaction within a transaction".

The stock can also change between adding to the cart and checking out, so checkout reads it again. In the check, Ana puts the Mug and the last Lamp in her cart. Ben then buys that Lamp with his own requests, and Ana places her order:

POST /api/cart {"product_id": 3, "quantity": 1}  (Ben)  →  200  {"items": [{"name": "Lamp", …}], "total": 29}
POST /api/checkout  (Ben)                       →  201  {"id": 8, "total": 29}
> click "Place order"  (Ana: Mug + Lamp)      →  POST /api/checkout -> 409, alert: Only 0 Lamp left
POST /api/checkout  (Ana, again)                →  409  {"error": "Only 0 Lamp left", "product_id": 3}
shop.db:  only order 8 is new;  stock: Mug 10, Lamp 0;  Ana's cart still holds the Mug and the Lamp

Your task: in the loop of POST /api/checkout in server/app.js, read each product's stock and answer 409 when there is too little; take the quantity off the stock; and wrap the order in BEGIN … COMMIT, with a ROLLBACK before the 409.


Assignment
Follow the Coding Tutorial to check the stock at checkout time, lower it, and make the order, its lines and the stock updates one transaction.


Hint
COMMIT goes below the loop, before the payment: a transaction shouldn't stay open while the server waits for the provider. ROLLBACK goes in the if, above the return.


STEP 1 OF 7
    Ctrl + Enter to check

    Fscheckout Transaction 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