bhylu.com

Advertisements

Node.js Stock Validation Exercise

A rejection should not partially apply the operation it refuses. Write assertions around the observable stock result before changing the implementation.

Your brief

The supporting domain project checks input shape and quantity before changing its Map. This exercise uses that actual helper and attempts an excessive request, then a valid one. The task is to explain the difference between validation, availability and idempotency rather than copying the implementation into a second test function. The complete project has no persistence and deliberately returns an explicit demo-only receipt.

Run the code

Run this example locally with Node.js. The exact sources are reviewed on Node 22.15.1 and Node 24.22.1 unless a specialised lab states otherwise. Save the complete source as exercises.mjs in a separate empty exercises folder and run node exercises.mjs. There is no Node.js browser runner on Bhylu; the plain JavaScript playground does not provide these filesystem, server or process APIs. Save the supporting project files below under a project subfolder beside this lesson source, preserving each filename.

Download the complete source. Ordinary Node scripts need no Apache, PHP or MySQL service. File examples own their temporary folders; network fixtures use loopback and available temporary ports.

Supporting project files

Save these files under project/ beside the downloaded lesson source. To run the complete service itself, follow project/README.md; npm test runs the actual domain tests and npm start uses an ephemeral write credential supplied by your own terminal.

Worked solution

Show the worked solution
exercises.mjs

import assert from 'node:assert/strict';
import { createDesk } from './project/desk.mjs';
const desk = createDesk();
assert.throws(
  () => desk.checkout({ key: 'too-many', kitId: 701, quantity: 4 }),
  (error) => error.status === 409,
);
assert.equal(desk.inventory()[0].available, 3);
assert.equal(desk.checkout({ key: 'valid-a', kitId: 701, quantity: 1 }).available, 2);
console.log('Rejected request preserved stock');

Expected result

Rejected request preserved stock

The rejected request leaves all three units, and the following accepted one leaves two. Tests should observe those outcomes instead of merely looking for a conditional in the source. The same invariants need persistence and concurrency tests before a real shared inventory is built.

Extend and test

Test an invalid key, unknown kit, fractional quantity and a replay with a changed payload. Confirm each has a deliberate result and no unintended decrement.

Use the Node.js API reference for the precise version contract.

Advertisements