Concept store: no payment is taken and nothing ships
Northline Supply Co. · storefront
A clothing store where the API keeps the rules.
A workwear shop with short runs and sizes that sell out. The page shows the clothes; a typed TypeScript API decides the prices, the stock, the discounts and whether an order goes through, the way a real store's server would.
- Role
- Product design, API design, build
- Platform
- Web storefront with a back office
- Built with
- TypeScript, Service Worker, IndexedDB
- Status
- Concept study · working store
01 / The brief
Small runs make the cart the hard part.
When a jacket comes in eight sizes and some of them have two left, the cart can't just add numbers in the browser. It has to know what's really in stock, which codes are really valid, and what happens when two people want the last one.
Prices, stock and discounts come from the server. A request that says a $148 jacket costs $1 still gets charged $148.
An expired code, a bad ZIP or a size that just sold out each get their own answer, so the shop can tell the customer what to do next.
A double-clicked "Place order" makes one order, and two shoppers racing for the last pair of trousers can't both win.
A concept study, honestly framed. Northline, its products, its prices and every order are fictional, and no payment is ever taken. There was no client and no user research. The API runs in your browser, inside a service worker, rather than on a server, and the back office has no login. Everything else (validation, pricing, stock, idempotent checkout) works as described and is covered by tests.
02 / Talk to it
Send the API a request. Watch it answer.
This console runs the store's real API code on this page, on its own copy of the catalogue. Pick a situation on the left, or edit the request and send your own.
Situations
Pick a situation, or press Send to fetch a product.
Responses appear here, newest first.
Long arrays are shortened for reading. In the store itself, the same code answers fetch("api/…") from a service worker, with its data in IndexedDB.
03 / The rules
One route table, one source of truth.
The API is shaped like a server: thirteen routes, each taking a method, a path and a JSON body and returning a status and JSON. TypeScript types describe the data, but types vanish at runtime, so every body is checked field by field before anything else happens.
- 01
Money is whole cents. No floating-point dollars anywhere; percentages round half up, once.
- 02
Prices are looked up, never trusted. The request names a variant and a quantity. Anything else in it is ignored.
- 03
Exact stock stays private. Shoppers see "in stock", "2 left" or "sold out"; only the back office sees the number.
- 04
Each failure has its own answer. 422 with field errors for bad input, 409 with what's left when stock runs out, 405 with the methods a path allows.
- 05
Checkout is idempotent. Every checkout carries a key; sending it again returns the first order instead of making a second.
- 06
Writes take turns. Checkouts and stock edits run one at a time, so the last unit can only be sold once.
- 07
Orders only move forward. Placed, packed, shipped. Anything else is a 409.
["POST", /^\/api\/checkout$/, (_m, body) => exclusive(async () => {
const r = parseCheckout(body);
if (!r.ok) return invalid(r.errors);
const req = r.value;
// Retrying the same checkout returns the same order instead of charging twice.
const prior = await db.get<Meta>("meta", "idem:" + req.idempotencyKey);
if (prior) { const o = await db.get<Order>("orders", String(prior.value)); return json(200, { order: o, replayed: true }); }
const c = await catalog();
const q = quote(req.lines, c.byVariant, c.byProduct, c.codes, req.code, req.shipping, today());
if ("error" in q) return json(q.status, q);
const changed = req.lines.map((l: CartLine) => { const v = c.byVariant.get(l.variantId)!; return Object.assign({}, v, { stock: v.stock - l.quantity }); });
const seq = ((await db.get<Meta>("meta", "orderSeq"))!.value as number) + 1;
const at = now().toISOString();
const order: Order = { id: "o-" + seq.toString(36) + "-" + Math.random().toString(36).slice(2, 8), number: "NL-" + seq, createdAt: at, email: req.email, address: req.address, quote: q, status: "placed", history: [{ status: "placed", at }] };
await db.putMany("variants", changed);
await db.put("orders", order);
await db.putMany<Meta>("meta", [{ key: "orderSeq", value: seq }, { key: "idem:" + req.idempotencyKey, value: order.id }]);
return json(201, { order });
})],
// Writes run one at a time, so two checkouts can't both buy the last jacket.
let lock: Promise<unknown> = Promise.resolve();
const exclusive = <T>(fn: () => Promise<T>): Promise<T> => { const run = lock.then(fn, fn); lock = run.catch(() => undefined); return run; };
04 / The store
A shop first, with the API underneath.
Everything a customer and a shop owner would touch, captured from the running store. Select any screen to see it larger.
05 / Try it
The real store, with a demo catalogue.
This demo keeps its own data, apart from the full store. Both live only in your browser.
- 1
Find a size with "2 left". Add three and watch the bag ask you to use two.
- 2
Try REPAIR15 on a small bag. It needs $100; the bag tells you how much more.
- 3
Place an order, then open the back office. Pack it, ship it, and see it in the API log.
No account, no payment, no server. Reset the demo from the back office.
Open the full store06 / How it's built
The API is written once and runs in three places.
The TypeScript in src/ compiles to one bundle. The service worker serves it to the store, this page's console calls it directly, and Node runs it in the tests, on an in-memory database.
- 516lines of TypeScript in src/, tests aside
- 13routes, shopper and back office
- 94variants across 9 products
- 11/11API tests passing
- A service worker as the serverThe store calls fetch("api/…") like any web app. The service worker intercepts it, runs the handler and returns a real Response with a status code, so the page can't tell it from a backend.
- IndexedDB behind an interfaceThe API talks to a small Db interface. In the browser that's IndexedDB; in tests it's memory. A server database would be one new class behind the same interface, plus real row locks.
- Validation at the boundaryEvery body is parsed into typed values or a list of field errors, with paths like address.zip that the checkout form maps straight to its inputs.
- A lock, tested by breaking itThe race test fires two checkouts for one unit at the same time. With the lock removed it fails, which is how I know it tests something.
- Fallback when there's no workerIf a browser blocks service workers, the store runs the same API in the page instead. The footer says which one is answering.
ok 1 - money is integer cents, formatted and rounded half up
ok 2 - the catalogue hides exact stock unless it is running low
ok 3 - prices come from the server, not the request
ok 4 - standard shipping is free from $75, express costs the difference
ok 5 - discount codes: percent, minimum spend, expired and unknown
ok 6 - bad bodies get 422 with field errors
ok 7 - a sold-out size returns 409 with what is left
ok 8 - checkout takes stock, numbers the order and is idempotent
ok 9 - two checkouts racing for the last unit: one wins, one gets 409
ok 10 - orders only move forward: placed, packed, shipped
ok 11 - unknown routes are 404, wrong methods 405, bad stock 422
# tests 11
# pass 11
# fail 0
07 / What I'd test next
What a real shop would ask of it.
The API behaves correctly in the browser and in tests. Real customers and a real server would test different things.
Put the same handler behind a real HTTP server and Postgres, with row locks instead of a single in-process lock, and run the race test against it.
Next: server adapter + databaseA real checkout needs a payment provider and its webhooks. The idempotency key already fits that shape; the order would wait for "paid" before taking stock.
Next: payment provider test mode"2 left" is meant to inform, not pressure. Watch whether shoppers trust it, and whether it changes what they buy.
Test: five-shopper sessionRight now anyone can open it, which is fine for a demo and not for a shop. It needs sign-in and roles before anything else.
Next: auth on admin routes