JS-230 · Lesson 12 of 12 · 38 min
Capstone: an order API
▶ Video coming soon A video version of this lesson is on the way.
On Thursday, April 13, 2028, Mira puts the partner service together for its review. Everything she has built in the last five weeks has been tested on its own: the routes, the middleware, the rules, the repository, the configuration, the logs. Today it becomes one program with one entry point that Theo can install, start, watch and stop, and that Rosa and three agencies will depend on. Gareth sets the bar: "By Tuesday's review, Theo should be able to deploy it without asking you a single question, and Rosa should be able to print Wednesday's sheet."
This capstone assembles the course. It restates the requirements and shows how each is met, lays out the project's files and the layers of the service, and builds the app with createApp from its parts. It writes server.js, the one file that touches the real world, with a clock in the kitchen's time zone and a clean shutdown. It adds Rosa's day sheet, runs a whole day of agency requests through an in-memory version of the service, and works through the deployment checklist with Theo. The lesson ends with the review on Tuesday, April 18, and the plan for the pilot.
What the service must do
Rosa's list from Lesson 3 and the rules gathered since then make a short specification. Every line has a place in the code and at least one test, named after the rule.
| Requirement | Where it is met | Lesson |
|---|---|---|
| Agencies see the menu | GET /menu, public | 4 |
| Agencies place, change and withdraw their own orders | POST, PATCH and DELETE /orders, behind requirePartner | 5, 8 |
| No agency can see or change another agency's orders | Every query filters by the caller's partner id; others get 404 | 7, 8 |
| Orders close at 12:00 two days before delivery | rules.js with the kitchen clock; 409 after | 6, 12 |
| Deliveries only on Mondays, Wednesdays and Fridays, up to 28 days ahead | rules.js; 409 otherwise | 6 |
| A day never passes its capacity, even with simultaneous orders | Transaction with FOR UPDATE on the day | 7 |
| A retried order never creates a duplicate | Idempotency-Key, unique per partner | 8 |
| Two people editing one order cannot lose a change | ETag and If-Match, 412 | 8 |
| Rosa sees what to cook for each day | GET /kitchen/days/:date, kitchen role | 12 |
| Problems are clear and consistent | Problem details for every error | 6 |
| Secrets never in code or logs | Config from the environment, redaction | 9, 11 |
The shape of the service
The service has a simple layered structure, the same shape as Theo's PHP application and most web back ends. Each layer only talks to the one below it, which is what made each lesson's work testable on its own.
partner-orders/
├── package.json "type": "module", scripts, three dependencies
├── package-lock.json
├── .env.example names of every variable, no real values
├── openapi.yaml the API description for the agencies
├── migrations/
│ ├── 001_create_partner_orders.sql
│ └── 002_add_order_version.sql
├── scripts/
│ └── remind.js the reminders script (Lessons 1, 2 and 9)
├── src/
│ ├── server.js reads config, builds real dependencies, starts and stops
│ ├── app.js createApp({ repo, clock, partners, logger })
│ ├── config.js checked, frozen configuration
│ ├── logger.js pino with redaction
│ ├── db.js the pg pool
│ ├── clock.js the kitchen's local time
│ ├── errors.js HttpError, ValidationError, RuleError
│ ├── schemas.js zod schemas for bodies and queries
│ ├── rules.js delivery days, cut-offs, 28-day window
│ ├── orders-repo.js all order SQL, transactions and locks
│ ├── partners-repo.js key lookup
│ ├── middleware/ request-id, timing, auth, validate, idempotent, errors
│ └── routes/ menu.js, orders.js, kitchen.js, health.js
└── test/
├── rules.test.js unit
├── orders.api.test.js API, with supertest and fakes
└── orders.db.test.js integration, against a test PostgreSQLWhat this code does
Each file has one job, and the folder names follow the layers: middleware and routes for HTTP, rules and schemas for the kitchen's rules, the two repositories for SQL and migrations for the database's structure. server.js and config.js are the only files that read the environment or start anything. Tests sit in their own folder, one file per level.
Building the app
createApp receives everything that differs between production and tests and returns a ready Express app. It contains the middleware order from Lesson 5 and the routes from Lesson 8, and nothing else. The order routes and the kitchen routes are built by factory functions that receive the repository and the clock, so the same code runs against PostgreSQL in production and the memory repository in tests.
// src/app.js
import express from 'express';
import helmet from 'helmet';
import cors from 'cors';
import { pinoHttp } from 'pino-http';
import { requestId } from './middleware/request-id.js';
import { makeAuth } from './middleware/auth.js';
import { rateLimit } from './middleware/rate-limit.js';
import { notFound, errorHandler } from './middleware/errors.js';
import { menuRouter } from './routes/menu.js';
import { makeOrdersRouter } from './routes/orders.js';
import { makeKitchenRouter } from './routes/kitchen.js';
import { makeHealthRouter } from './routes/health.js';
export function createApp({ repo, partners, clock, logger, config, checkDb }) {
const app = express();
app.disable('x-powered-by');
app.set('trust proxy', 'loopback'); // Theo's web server on the same machine sets X-Forwarded-For
app.use(requestId);
app.use(pinoHttp({ logger, genReqId: (req) => req.id }));
app.use(helmet());
app.use(cors({ origin: config.corsOrigins, allowedHeaders: ['Authorization', 'Content-Type', 'Idempotency-Key', 'If-Match'] }));
app.use(express.json({ limit: '10kb' }));
const auth = makeAuth(partners);
const v1 = express.Router();
v1.use('/menu', menuRouter);
v1.use('/orders', auth.requirePartner, rateLimit({ perMinute: 60 }), makeOrdersRouter({ repo, clock }));
v1.use('/kitchen', auth.requirePartner, auth.requireRole('kitchen'), makeKitchenRouter({ repo, clock }));
app.use('/healthz', makeHealthRouter({ checkDb }));
app.use('/api/partners/v1', v1);
app.use(notFound);
app.use(errorHandler);
return app;
}What this code does
createApp builds the chain in the order the lessons established, from request ids to the error handler. Its arguments are the repository, the partner lookup, the clock, the logger, the configuration and a database check, so nothing inside it reaches for a global. trust proxy is set only for a web server on the same machine, which lets the rate limit and the logs see the agency's real address rather than the proxy's.
The kitchen clock
The cut-off rule is written in the kitchen's wall-clock time: noon in Kingston, not noon in UTC. The server's operating system runs in UTC, as most servers do, so the service must convert. When the clocks change for daylight saving time in March and November, the offset between UTC and the kitchen changes from one hour to the next, which is exactly the kind of detail that should not be calculated by hand. JavaScript's Intl API knows every time zone's rules; Temporal, enabled by default in Node 26 and in recent browsers, makes the same job simpler, and the service uses it when it is there.
function kitchenTime(date, timeZone) {
const fmt = new Intl.DateTimeFormat('en-CA', { timeZone, year: 'numeric', month: '2-digit', day: '2-digit',
hour: '2-digit', minute: '2-digit', hourCycle: 'h23' });
const p = Object.fromEntries(fmt.formatToParts(date).map((x) => [x.type, x.value]));
return `${p.year}-${p.month}-${p.day}T${p.hour}:${p.minute}`;
}
const zones = ['America/Toronto', 'America/Chicago', 'UTC'];
const moments = [
'2028-03-11T16:30:00Z', // Saturday, before the clocks change
'2028-03-13T16:30:00Z', // Monday, after the change to daylight time
'2028-11-06T16:30:00Z', // Monday, after the change back
];
for (const m of moments) {
console.log(m, '->', zones.map((z) => `${z}: ${kitchenTime(new Date(m), z)}`).join(' '));
}2028-03-11T16:30:00Z -> America/Toronto: 2028-03-11T11:30 America/Chicago: 2028-03-11T10:30 UTC: 2028-03-11T16:30 2028-03-13T16:30:00Z -> America/Toronto: 2028-03-13T12:30 America/Chicago: 2028-03-13T11:30 UTC: 2028-03-13T16:30 2028-11-06T16:30:00Z -> America/Toronto: 2028-11-06T11:30 America/Chicago: 2028-11-06T10:30 UTC: 2028-11-06T16:30
What this code does
kitchenTime asks Intl.DateTimeFormat for the year, month, day, hour and minute of a moment in a given time zone and joins them into the same text format the rules use. The same UTC time, 16:30, is a different local time before and after the clocks change, because the zone's offset changes. Letting Intl apply the zone's rules means the cut-off is noon in the kitchen on every day of the year.
// src/clock.js — the kitchen's wall-clock time as 'YYYY-MM-DDTHH:MM'
export function kitchenClock(timeZone) {
if (globalThis.Temporal) {
return () => Temporal.Now.zonedDateTimeISO(timeZone).toPlainDateTime().toString().slice(0, 16);
}
const fmt = new Intl.DateTimeFormat('en-CA', { timeZone, year: 'numeric', month: '2-digit', day: '2-digit',
hour: '2-digit', minute: '2-digit', hourCycle: 'h23' });
return () => {
const p = Object.fromEntries(fmt.formatToParts(new Date()).map((x) => [x.type, x.value]));
return `${p.year}-${p.month}-${p.day}T${p.hour}:${p.minute}`;
};
}What this code does
kitchenClock returns a function that gives the current kitchen time in the rules' format, using Temporal when the Node version has it and Intl otherwise. The formatter is created once, because creating Intl formatters is slow compared with using them. In tests, the clock is replaced with a function that returns a fixed time.
Starting and stopping
server.js is the only file that knows about the outside world. It loads the checked configuration, builds the real dependencies, starts the server and handles shutdown. The service listens on 127.0.0.1, not on every network address, because only Theo's web server on the same machine should reach it; the web server handles HTTPS and forwards requests under /api/partners/ to port 3100. The shutdown handler is the pattern from Lesson 1: on SIGTERM it stops accepting connections, lets requests in progress finish, closes the database pool and exits, with a timer that forces an exit if something hangs.
// src/server.js — the only file that touches the real world
import { config } from './config.js';
import { logger } from './logger.js';
import { pool } from './db.js';
import { createApp } from './app.js';
import * as repo from './orders-repo.js';
import * as partners from './partners-repo.js';
import { kitchenClock } from './clock.js';
const app = createApp({
repo, partners, logger, config,
clock: kitchenClock(config.kitchenTimeZone),
checkDb: () => pool.query('SELECT 1'),
});
const server = app.listen(config.port, '127.0.0.1', () => {
logger.info({ port: config.port, node: process.version }, 'partner-orders listening');
});
server.keepAliveTimeout = 65_000; // longer than the web server's idle timeout in front of it
let stopping = false;
async function shutdown(signal) {
if (stopping) return;
stopping = true;
logger.info({ signal }, 'shutting down');
const force = setTimeout(() => { logger.error('forced exit after 10 s'); process.exit(1); }, 10_000);
force.unref();
server.close(async () => { // stop accepting; wait for requests in progress
await pool.end(); // close database connections
logger.info('stopped cleanly');
process.exitCode = 0;
});
server.closeIdleConnections();
}
process.on('SIGTERM', () => shutdown('SIGTERM'));
process.on('SIGINT', () => shutdown('SIGINT'));
process.on('unhandledRejection', (err) => { logger.fatal({ err }, 'unhandled rejection'); process.exit(1); });What this code does
The app is built with the real repository, partner lookup, logger and kitchen clock, and the health check runs SELECT 1 against the pool. The server listens only on the local address, and its keep-alive timeout is longer than the web server's so the two never close the same idle connection at once. shutdown runs once, closes the server and then the pool, and a timer that does not keep the process alive by itself forces an exit after 10 seconds.
Rosa's day sheet
The last route is the one Rosa asked for first. GET /api/partners/v1/kitchen/days/2028-04-19 returns everything the kitchen needs for that delivery: the trays of each item, the total against the day's capacity, whether the cut-off has passed and the sheet is final, and the list of orders with each agency's name, lines and note. The kitchen tablet shows it and prints it. Only the kitchen's key, with the kitchen role, can read it.
// src/routes/kitchen.js
import { Router } from 'express';
import * as z from 'zod';
import { HttpError } from '../errors.js';
import { cutoffFor } from '../rules.js';
export function makeKitchenRouter({ repo, clock }) {
const router = Router();
router.get('/days/:date', async (req, res) => {
const date = z.iso.date().safeParse(req.params.date);
if (!date.success) throw new HttpError(422, 'Your request has some problems', 'date must be YYYY-MM-DD');
const orders = await repo.listForDay(date.data); // received orders only, with partner names
const totals = { soup: 0, stew: 0, sandwiches: 0 };
for (const o of orders) for (const l of o.lines) totals[l.item] += l.trays;
const trays = totals.soup + totals.stew + totals.sandwiches;
res.json({
date: date.data,
closed: clock() >= cutoffFor(date.data), // after the cut-off, the sheet is final
totals, trays, capacity: await repo.capacityFor(date.data),
orders: orders.map((o) => ({ id: o.id, partner: o.partnerName, lines: o.lines, note: o.note })),
});
});
return router;
}What this code does
The route checks that the date is a real date, asks the repository for the day's received orders and adds up the trays of each item. closed is true once the kitchen clock has passed the cut-off, which tells Rosa the numbers will not change any more. Each order appears with the agency's name, which the repository joins in, so the kitchen sees who each delivery is for.
function daySheet(date, orders, capacity) {
const totals = { soup: 0, stew: 0, sandwiches: 0 };
const received = orders.filter((o) => o.deliveryDate === date && o.status === 'received');
for (const o of received) for (const l of o.lines) totals[l.item] += l.trays;
const trays = Object.values(totals).reduce((a, b) => a + b, 0);
const servings = totals.soup * 12 + totals.stew * 10 + totals.sandwiches * 12;
return { date, totals, trays, capacity, servings, deliveries: received.map((o) => o.partner) };
}
const orders = [
{ partner: 'Northside Family Shelter', deliveryDate: '2028-04-19', status: 'received', lines: [{ item: 'soup', trays: 6 }, { item: 'sandwiches', trays: 3 }] },
{ partner: 'Elm Street Seniors Club', deliveryDate: '2028-04-19', status: 'received', lines: [{ item: 'stew', trays: 4 }, { item: 'soup', trays: 2 }] },
{ partner: 'Westview Youth Drop-In', deliveryDate: '2028-04-19', status: 'withdrawn', lines: [{ item: 'sandwiches', trays: 5 }] },
{ partner: 'Westview Youth Drop-In', deliveryDate: '2028-04-21', status: 'received', lines: [{ item: 'soup', trays: 3 }] },
];
console.log(daySheet('2028-04-19', orders, 40));{ date: "2028-04-19", totals: { soup: 8, stew: 4, sandwiches: 3 }, trays: 15, capacity: 40, servings: 172, deliveries: [ "Northside Family Shelter", "Elm Street Seniors Club" ] }What this code does
daySheet keeps only the received orders for the date, so the withdrawn order and the Friday order are left out. It adds up the trays per item, then the total, and works out the servings from 12 per tray of soup or sandwiches and 10 per tray of stew. The result is what the kitchen tablet shows: 8 trays of soup, 4 of stew and 3 of sandwiches, 15 of 40 trays and 172 servings for two deliveries.
A day of requests
Before the review, Gareth asks for one more check: a whole morning of agency requests, in order, through a version of the service that uses the memory repository and a fixed clock. The example is a compact but complete model of the real service: a route table, authentication by key, validation, the rules, capacity, idempotency and problem details, all in one runnable program.
const KEYS = { 'key-n': { id: 1, slug: 'northside' }, 'key-e': { id: 2, slug: 'elm-seniors' }, 'key-k': { id: 9, slug: 'kitchen', role: 'kitchen' } };
const ITEMS = ['soup', 'stew', 'sandwiches'];
let now = '2028-04-17T09:00';
const orders = []; const seen = new Map(); let nextId = 101;
const cutoff = (d) => new Date(Date.parse(d + 'T12:00:00Z') - 2 * 86_400_000).toISOString().slice(0, 16);
const used = (d) => orders.filter((o) => o.date === d && o.status === 'received').reduce((s, o) => s + o.lines.reduce((a, l) => a + l.trays, 0), 0);
const problem = (status, title, extra = {}) => ({ status, body: { title, status, ...extra } });
function handle({ method, path, key, idem, body }) {
const who = KEYS[key];
if (!who) return problem(401, 'missing or unknown API key');
const [, , id] = path.split('/');
if (method === 'POST' && path === '/orders') {
if (!idem) return problem(400, 'Idempotency-Key header is required');
const mark = `${who.id}:${idem}`;
if (seen.has(mark)) return { ...seen.get(mark), replayed: true };
const bad = (body.lines ?? []).filter((l) => !ITEMS.includes(l.item) || !Number.isInteger(l.trays) || l.trays < 1 || l.trays > 10);
if (!body.date || !body.lines?.length || bad.length) return problem(422, 'Your request has some problems');
if (![1, 3, 5].includes(new Date(body.date + 'T00:00:00Z').getUTCDay())) return problem(409, 'not a delivery day');
if (now >= cutoff(body.date)) return problem(409, 'cut-off passed', { detail: `closed ${cutoff(body.date)}` });
const wanted = body.lines.reduce((a, l) => a + l.trays, 0);
if (used(body.date) + wanted > 40) return problem(409, 'not enough capacity', { detail: `${40 - used(body.date)} trays left` });
const order = { id: nextId++, partner: who.id, status: 'received', ...body };
orders.push(order);
const res = { status: 201, body: { id: order.id, trays: wanted } };
seen.set(mark, res);
return res;
}
if (method === 'DELETE' && id) {
const o = orders.find((x) => x.id === Number(id) && x.partner === who.id);
if (!o) return problem(404, 'Not found');
if (now >= cutoff(o.date)) return problem(409, 'cut-off passed');
o.status = 'withdrawn';
return { status: 204 };
}
if (method === 'GET' && path.startsWith('/kitchen/days/')) {
if (who.role !== 'kitchen') return problem(403, 'needs the kitchen role');
const date = path.slice('/kitchen/days/'.length);
return { status: 200, body: { trays: used(date), closed: now >= cutoff(date) } };
}
return problem(404, 'Not found');
}
const day = [
['09:00', { method: 'POST', path: '/orders', key: 'key-n', idem: 'n1', body: { date: '2028-04-19', lines: [{ item: 'soup', trays: 10 }, { item: 'stew', trays: 10 }] } }],
['09:00', { method: 'POST', path: '/orders', key: 'key-n', idem: 'n1', body: { date: '2028-04-19', lines: [{ item: 'soup', trays: 10 }, { item: 'stew', trays: 10 }] } }],
['09:20', { method: 'POST', path: '/orders', key: 'key-e', idem: 'e1', body: { date: '2028-04-19', lines: [{ item: 'soup', trays: 10 }, { item: 'sandwiches', trays: 10 }, { item: 'stew', trays: 2 }] } }],
['09:25', { method: 'POST', path: '/orders', key: 'key-e', idem: 'e2', body: { date: '2028-04-19', lines: [{ item: 'soup', trays: 10 }, { item: 'sandwiches', trays: 10 }] } }],
['10:05', { method: 'GET', path: '/orders/101', key: 'key-x' }],
['10:10', { method: 'GET', path: '/kitchen/days/2028-04-19', key: 'key-e' }],
['11:30', { method: 'DELETE', path: '/orders/101', key: 'key-e' }],
['11:45', { method: 'DELETE', path: '/orders/101', key: 'key-n' }],
['11:50', { method: 'POST', path: '/orders', key: 'key-e', idem: 'e3', body: { date: '2028-04-19', lines: [{ item: 'soup', trays: 10 }, { item: 'sandwiches', trays: 8 }] } }],
['12:00', { method: 'POST', path: '/orders', key: 'key-n', idem: 'n2', body: { date: '2028-04-19', lines: [{ item: 'soup', trays: 2 }] } }],
['12:01', { method: 'GET', path: '/kitchen/days/2028-04-19', key: 'key-k' }],
];
for (const [time, req] of day) {
now = `2028-04-17T${time}`;
const res = handle(req);
console.log(time, req.method.padEnd(6), req.path.padEnd(25), res.status, JSON.stringify(res.body ?? ''), res.replayed ? '(replayed)' : '');
}09:00 POST /orders 201 {"id":101,"trays":20}
09:00 POST /orders 201 {"id":101,"trays":20} (replayed)
09:20 POST /orders 409 {"title":"not enough capacity","status":409,"detail":"20 trays left"}
09:25 POST /orders 201 {"id":102,"trays":20}
10:05 GET /orders/101 401 {"title":"missing or unknown API key","status":401}
10:10 GET /kitchen/days/2028-04-19 403 {"title":"needs the kitchen role","status":403}
11:30 DELETE /orders/101 404 {"title":"Not found","status":404}
11:45 DELETE /orders/101 204 ""
11:50 POST /orders 201 {"id":103,"trays":18}
12:00 POST /orders 409 {"title":"cut-off passed","status":409,"detail":"closed 2028-04-17T12:00"}
12:01 GET /kitchen/days/2028-04-19 200 {"trays":38,"closed":true}What this code does
The model handles each request in order with the clock set to the time in the first column, and every line shows the status and body the real service would send. Northside's retry is replayed instead of creating a second order, and Elm Street's first order is refused because only 20 trays are left, so a smaller one fits. Only the kitchen may read the day sheet, and Elm Street cannot withdraw Northside's order, which it is told does not exist; once Northside withdraws it, Elm Street's third order fits. At noon the Wednesday cut-off has passed, so the next order is refused and the sheet is closed at 38 trays.
Every line of that output corresponds to a test in the real service's test folder. The model is not the service, because it has no HTTP, no database and no concurrency, but it shows in one place how the rules work together, and Rosa found it easier to check than the code: she read the eleven lines and confirmed each answer was what the kitchen would want.
Deploying with Theo
On Friday, April 14, Theo and Mira go through his deployment checklist on the staging server, the same steps he will repeat for production. Most items are things the course has already built; the checklist makes sure none is forgotten.
| Step | How |
|---|---|
| Node | Install the current LTS (Node 27) from the official packages; record it in .nvmrc and engines |
| Code | git fetch of a tagged release into /srv/partner-orders; npm ci --omit=dev |
| Database | Schema and partner_app role created by Theo; migrations run with the migration role |
| Configuration | /etc/partner-orders/env, readable only by the service user; checked at start-up |
| Process | systemd unit with Restart=on-failure, its own user and the environment file |
| Network | Listen on 127.0.0.1:3100; Theo's web server terminates HTTPS and forwards /api/partners/ |
| Logs | JSON to standard output, collected by the journal and kept 90 days |
| Monitoring | GET /healthz every minute; a text to Theo after three failures |
| Backups | Covered by the managed database's point-in-time recovery (WEB-201) |
| Keys | One key per agency and one for the kitchen, created by Theo and sent by phone, not email |
systemctl status partner-orders --no-pager | head -3● partner-orders.service - Riverside partner order API
Loaded: loaded (/etc/systemd/system/partner-orders.service; enabled; preset: enabled)
Active: active (running) since Fri 2028-04-14 19:41:09 UTC; 12min agoWhat this code does
systemctl status shows whether the service is running, since when, and the unit file it was started from. Theo checks it after every deployment, then calls the health check and reads the first log lines. The server keeps its clock in UTC, so the time shown is UTC, not kitchen time.
Deploying a new version follows the same steps with one addition: migrations run before the new code starts, and every migration is written so that the old code still works with the new database for the few seconds both exist. Adding a column is safe; renaming one takes two releases. systemctl restart sends SIGTERM to the old process, which finishes its requests and stops, and starts the new one, which checks its configuration and begins listening, all in about a second.
The review
On Tuesday, April 18, Mira presents the service to Theo, Rosa and Gareth. Rosa places orders from the kitchen tablet and from a test agency account, prints Wednesday's sheet and tries her four orders from Lesson 6 again; each is refused with a message she understands. Theo reviews the code and the deployment and asks for three changes before the pilot.
- A statement timeout. A query that hangs, for example behind a lock nobody releases, should fail after 5 seconds instead of holding a connection forever. One line in the pool's options sets statement_timeout.
- A hard cap on list limits. The schema accepted limit=100, but nothing stopped a crafted request from asking for limit=100000 through a bug in the default handling. The schema now refuses anything over 100 and a test proves it.
- A second kitchen key. Rosa's tablet and the office computer share one key, so revoking a lost tablet's key would cut off the office too. Each device now gets its own key with the kitchen role.
Gareth asks Mira what she would change with more time. Her answer is a list for the next block: email notifications to agencies when an order is confirmed or refused, a weekly print sheet for the kitchen, and moving the reminders script onto the same structured logger. Rosa asks the question that matters most to her: whether the agencies can start in May. Theo checks his calendar.
| Date (2028) | Plan |
|---|---|
| Wednesday, April 19 | Theo's three changes merged and deployed to staging |
| Monday, April 24 | Production deployment; Rosa and Lucy test with the kitchen keys |
| Tuesday, April 25 | Theo phones each agency with its key; Mira walks their coordinators through the form |
| Monday, May 1 | Pilot: agencies order online for deliveries from Wednesday, May 3; phone orders still accepted |
| Friday, May 26 | Pilot review with Rosa and the agencies; phone orders end if all goes well |
| June 2028 | JS-240: notifications, authentication and real-time updates for the kitchen screen |
Worked problem
Will one process be enough?
In the pilot, each of the three agencies places about 3 orders a week and changes 2 of them, and each order and change takes about 4 requests through the form. Rosa's kitchen screen refreshes the day sheet every 60 seconds from 07:00 to 15:00, five days a week. Each request uses about 2 ms of JavaScript time. How many requests a week is that, and how busy is the one Node process?
Show solution
- Agency requests: 3 agencies × (3 orders + 2 changes) × 4 requests = 60 a week.
- Kitchen screen: 8 hours × 60 refreshes = 480 a day; × 5 days = 2,400 a week.
- Total: 60 + 2,400 = 2,460 requests a week.
- JavaScript time: 2,460 × 2 ms = 4,920 ms, about 5 seconds a week.
- A week has 7 × 24 × 3,600 = 604,800 seconds, so the process is busy for about 5 in every 604,800 seconds.
Answer: About 2,460 requests a week, almost all of them from the kitchen screen, using about 5 seconds of processor time in total. One process is far more than enough; the limits that matter are correctness, security and staying up, which is where the course spent its time.
Common mistakes
MistakeThe capstone is done when the routes work.
InsteadIt is done when it can be deployed, configured, watched, stopped and changed safely by someone else.
MistakeThe cut-off can be checked against the server's clock.
InsteadThe server runs in UTC. Convert to the kitchen's time zone with Intl or Temporal.
MistakeA service behind a web server can listen on every address.
InsteadListen on 127.0.0.1 so only the web server on the same machine can reach it.
MistakeRestarting the service may lose a few requests; that is normal.
InsteadHandle SIGTERM: stop accepting, finish requests in progress, close the pool, then exit.
Summary and key terms
- The partner order API is a small, layered Node service: Express and middleware for HTTP, short route handlers, zod schemas and a rules module, and a repository that holds all SQL, with PostgreSQL underneath. createApp builds the app from its dependencies, so tests can use fakes, and server.js is the only file that reads the configuration, creates the real pool, logger and kitchen clock, listens on the local address and shuts down cleanly on SIGTERM.
- The kitchen clock turns the server's UTC time into the kitchen's local time with Intl or Temporal, so the cut-off is right on every day of the year.
- Rosa's day sheet adds up each item's trays for a delivery day and shows whether the cut-off has passed.
- Deployment follows a checklist covering the Node version, installation, migrations, configuration, the systemd unit, the network, logs, monitoring, backups and keys.
- The review led to three hardening changes and a pilot with the three agencies from May 2028.
- Layered architecture
- A structure in which each part of a program talks only to the layer below it.
- Entry point
- The file that starts a program; for the service, server.js.
- Factory function
- A function that builds and returns an object, such as createApp or makeOrdersRouter.
- Time zone
- A region with its own rules for converting UTC to local time, including daylight saving changes.
- Temporal
- JavaScript's modern date and time API, enabled by default in Node 26.
- Graceful shutdown
- Stopping a server by refusing new work, finishing work in progress and closing connections.
- Reverse proxy
- A web server that receives requests from the internet and forwards them to a service behind it.
- Statement timeout
- A database setting that cancels any query running longer than a set time.
- Pilot
- A limited first use of a new system by real users, with the old way still available.
Practice problems
Work each problem on paper first, then reveal the answer to check.
Which file is the only one that reads the environment and starts the server?
Show answer
src/server.js, together with config.js, which it imports.
Why does the service listen on 127.0.0.1?
Show answer
So that only Theo's web server on the same machine can reach it.
Why can the kitchen clock not just use the server's time?
Show answer
The server runs in UTC and the cut-off is in the kitchen's local time, which changes offset with daylight saving time.
What does the service do when it receives SIGTERM?
Show answer
It stops accepting connections, lets requests in progress finish, closes the pool and exits.
Name one of Theo's three changes and the risk it removes.
Show answer
A statement timeout, so a hung query cannot hold a connection forever; or a hard cap on list limits; or one kitchen key per device.
Try it yourself
Build the day sheet
Complete daySheet(date, orders, capacity). It returns { date, totals, trays, left, deliveries } for received orders on that date only: totals maps soup, stew and sandwiches to their trays (0 if none), trays is the sum, left is capacity - trays but never below 0, and deliveries lists the partners in order of their order id, without repeats.
Orders have id, partner, date, status and lines.
function daySheet(date, orders, capacity) {
return { date };
}
const orders = [
{ id: 107, partner: 'Westview', date: '2028-04-19', status: 'received', lines: [{ item: 'sandwiches', trays: 4 }] },
{ id: 102, partner: 'Northside', date: '2028-04-19', status: 'received', lines: [{ item: 'soup', trays: 10 }, { item: 'stew', trays: 6 }] },
{ id: 104, partner: 'Elm Street', date: '2028-04-19', status: 'withdrawn', lines: [{ item: 'soup', trays: 8 }] },
{ id: 105, partner: 'Northside', date: '2028-04-19', status: 'received', lines: [{ item: 'soup', trays: 2 }] },
{ id: 106, partner: 'Elm Street', date: '2028-04-21', status: 'received', lines: [{ item: 'stew', trays: 3 }] },
];
console.log(daySheet('2028-04-19', orders, 40));
console.log(daySheet('2028-04-19', orders, 20));
console.log(daySheet('2028-04-24', orders, 40));Try it yourself
May this order still change?
Complete canChange(order, newDate, now). An order may be changed if it is received, the cut-off for its current date has not passed and, when newDate is given and differs, the cut-off for the new date has not passed either. The cut-off is 12:00 two days before delivery; times are written YYYY-MM-DDTHH:MM.
Return 'ok', or the first reason it may not change: 'withdrawn' (status not received), 'closed' (current date's cut-off passed) or 'new date closed'.
function cutoff(date) {
return new Date(Date.parse(date + 'T12:00:00Z') - 2 * 86_400_000).toISOString().slice(0, 16);
}
function canChange(order, newDate, now) {
return 'ok';
}
const o = { status: 'received', date: '2028-04-21' }; // Friday; cut-off Wednesday 12:00
console.log(canChange(o, null, '2028-04-19T11:59'));
console.log(canChange(o, null, '2028-04-19T12:00'));
console.log(canChange(o, '2028-04-24', '2028-04-19T09:00'));
console.log(canChange(o, '2028-04-19', '2028-04-17T13:00'));
console.log(canChange({ ...o, status: 'withdrawn' }, null, '2028-04-17T09:00'));
console.log(canChange(o, '2028-04-21', '2028-04-19T11:00'));Lesson quiz · 5 questions
Score 60% or more to complete this lesson.
Create a free account to save your progress, take quizzes and earn a certificate.