Module 3 · Build real CRUD features
3.5 Inspections, a state machine and transactions
Add inspections with a draft → submitted → approved workflow, enforce valid transitions with a conditional UPDATE, and record history atomically in a transaction.
Starting point
Organisations, buildings and issues have full CRUD. The schema has three tables and one migration.
Outcome
migrations/002_create_inspections.sqlsrc/models/inspections.js src/routes/inspections.jsviews/inspections/ index.ejs show.ejs form.ejstest/inspections.test.jsInspections move through a small workflow:
Each transition updates the inspection and writes a row to inspection_status_changes, in one transaction. Two people pressing "Approve" at the same moment cannot both succeed.
The problem
An inspection is not just a record with a status column. Its status follows rules: you cannot approve a draft, you cannot edit an approved inspection, and every change of status must be recorded so you can tell who did what and when (we add "who" in Module 4).
Two traps hide in the obvious implementation:
- Check-then-act. "Load the inspection; if its status is
submitted, update it toapproved" is two steps. Two requests can both loadsubmitted, both pass the check, and both approve. - Half-finished work. "Update the inspection; then insert a history row" is two statements. If the second fails, the inspection is approved with no history.
The database solves both: a conditional UPDATE checks and changes in one atomic statement, and a transaction makes several statements succeed or fail together.
Build it
1. The migration
CREATE TABLE inspections ( id integer GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY, building_id integer NOT NULL REFERENCES buildings (id) ON DELETE RESTRICT, title text NOT NULL CHECK (length(title) BETWEEN 3 AND 200), findings text NOT NULL DEFAULT '', status text NOT NULL DEFAULT 'draft' CHECK (status IN ('draft', 'submitted', 'approved')), submitted_at timestamptz, approved_at timestamptz, created_at timestamptz NOT NULL DEFAULT now(), updated_at timestamptz NOT NULL DEFAULT now()); CREATE INDEX inspections_building_id_idx ON inspections (building_id); CREATE TABLE inspection_status_changes ( id integer GENERATED ALWAYS AS IDENTITY PRIMARY KEY, inspection_id integer NOT NULL REFERENCES inspections (id) ON DELETE CASCADE, from_status text NOT NULL, to_status text NOT NULL, changed_at timestamptz NOT NULL DEFAULT now()); CREATE INDEX inspection_status_changes_inspection_id_idx ON inspection_status_changes (inspection_id);statushas aCHECKwith the three states. The transitions between them are rules about changes, which aCHECKcannot express; the application enforces those.- History rows use
ON DELETE CASCADE: history belongs to its inspection. (The app never deletes inspections, but the schema says what would happen.) GENERATED ALWAYSfor history IDs: nobody should ever choose a history row's ID, so we do not allow it.
npm run db:migrate
> caretaker@1.0.0 db:migrate
> node --env-file=.env scripts/migrate.js
applied 002_create_inspections.sql
migrations are up to date
2. Seed the scenario's inspections
Add the four inspections from our scenario to src/seed.js:
export const issues = [...namedIssues, ...fillerIssues()]; export const inspections = [ { id: 201, buildingId: 10, title: 'Q4 lift maintenance inspection', status: 'submitted', findings: 'Service log not signed for October. Emergency phone in lift 2 needs a new battery.' }, { id: 202, buildingId: 10, title: 'Roof and gutter check, all four sides', status: 'submitted', findings: 'One blocked gutter on the north side.' }, { id: 203, buildingId: 20, title: 'Door and lock check', status: 'draft', findings: '' }, { id: 204, buildingId: 30, title: 'Boiler room review', status: 'draft', findings: '' },];
await client.query('TRUNCATE issues, buildings, organisations RESTART IDENTITY CASCADE'); await client.query('TRUNCATE inspection_status_changes, inspections, issues, buildings, organisations RESTART IDENTITY CASCADE');
for (const table of ['organisations', 'buildings', 'issues']) { for (const a of inspections) { await client.query( `INSERT INTO inspections (id, building_id, title, findings, status, submitted_at) VALUES ($1, $2, $3, $4, $5, CASE WHEN $5 = 'submitted' THEN now() END)`, [a.id, a.buildingId, a.title, a.findings, a.status], ); if (a.status === 'submitted') { await client.query("INSERT INTO inspection_status_changes (inspection_id, from_status, to_status) VALUES ($1, 'draft', 'submitted')", [a.id]); } } for (const table of ['organisations', 'buildings', 'issues', 'inspections']) {
Show the whole src/seed.js after this change
export const organisations = [ { id: 1, name: 'Liffey Estates' }, { id: 2, name: 'Harbour Lets' },]; export const buildings = [ { id: 10, organisationId: 1, name: 'Dublin Offices' }, { id: 20, organisationId: 1, name: 'Cork Apartments' }, { id: 30, organisationId: 2, name: 'Galway Studios' }, { id: 40, organisationId: 2, name: 'Limerick House' },]; const namedIssues = [ { id: 101, buildingId: 10, title: 'Lift stuck between floors 2 and 3', priority: 'high', status: 'open', occurredAt: '2026-11-02T09:15:00Z', description: 'The lift stopped between floors with nobody inside. Engineer called.' }, { id: 102, buildingId: 10, title: 'Dripping tap in the second-floor kitchen', priority: 'low', status: 'closed', occurredAt: '2026-11-05T14:40:00Z', description: 'Worn washer. Tap replaced and floor dried.' }, { id: 103, buildingId: 20, title: 'Front door lock sticks at entrance 4', priority: 'medium', status: 'open', occurredAt: '2026-11-08T07:05:00Z', description: 'The key turns only after several tries.' }, { id: 104, buildingId: 20, title: 'Water stain on the ceiling of flat 7', priority: 'high', status: 'investigating', occurredAt: '2026-11-10T11:30:00Z', description: 'Stain about 40 cm wide. Roof drain to be checked.' }, { id: 105, buildingId: 30, title: 'Boiler lost pressure in plant room', priority: 'critical', status: 'open', occurredAt: '2026-11-11T06:50:00Z', description: 'No heating on the ground floor.' }, { id: 106, buildingId: 40, title: 'Car park barrier stuck open', priority: 'low', status: 'open', occurredAt: '2026-11-12T16:20:00Z', description: '' },]; const fillerTitles = [ 'Loose handrail on stairs', 'Bins not collected', 'Corridor light not working', 'Radiator cold in room 2', 'Window does not close fully', 'Loose floor tile at entrance', 'Toilet cistern keeps running', 'Blocked sink in kitchen',]; // 24 extra issues (ids 107-130) alternate between buildings 10 and 20,// so that lists have enough rows to page, sort and filter.function fillerIssues() { const priorities = ['low', 'medium', 'high', 'critical']; const statuses = ['open', 'investigating', 'closed']; const issues = []; for (let i = 0; i < 24; i++) { issues.push({ id: 107 + i, buildingId: i % 2 === 0 ? 10 : 20, title: `${fillerTitles[i % fillerTitles.length]} (#${107 + i})`, priority: priorities[i % priorities.length], status: statuses[i % statuses.length], occurredAt: new Date(Date.UTC(2026, 9, 1 + i, 8 + (i % 9))).toISOString(), description: '', }); } return issues;} export const issues = [...namedIssues, ...fillerIssues()]; export const inspections = [ { id: 201, buildingId: 10, title: 'Q4 lift maintenance inspection', status: 'submitted', findings: 'Service log not signed for October. Emergency phone in lift 2 needs a new battery.' }, { id: 202, buildingId: 10, title: 'Roof and gutter check, all four sides', status: 'submitted', findings: 'One blocked gutter on the north side.' }, { id: 203, buildingId: 20, title: 'Door and lock check', status: 'draft', findings: '' }, { id: 204, buildingId: 30, title: 'Boiler room review', status: 'draft', findings: '' },]; export async function seed(client) { await client.query('BEGIN'); try { await client.query('TRUNCATE inspection_status_changes, inspections, issues, buildings, organisations RESTART IDENTITY CASCADE'); for (const o of organisations) { await client.query('INSERT INTO organisations (id, name) VALUES ($1, $2)', [o.id, o.name]); } for (const s of buildings) { await client.query('INSERT INTO buildings (id, organisation_id, name) VALUES ($1, $2, $3)', [s.id, s.organisationId, s.name]); } for (const e of issues) { await client.query( `INSERT INTO issues (id, building_id, title, description, priority, status, occurred_at) VALUES ($1, $2, $3, $4, $5, $6, $7)`, [e.id, e.buildingId, e.title, e.description, e.priority, e.status, e.occurredAt], ); } for (const a of inspections) { await client.query( `INSERT INTO inspections (id, building_id, title, findings, status, submitted_at) VALUES ($1, $2, $3, $4, $5, CASE WHEN $5 = 'submitted' THEN now() END)`, [a.id, a.buildingId, a.title, a.findings, a.status], ); if (a.status === 'submitted') { await client.query("INSERT INTO inspection_status_changes (inspection_id, from_status, to_status) VALUES ($1, 'draft', 'submitted')", [a.id]); } } for (const table of ['organisations', 'buildings', 'issues', 'inspections']) { await client.query(`SELECT setval(pg_get_serial_sequence($1, 'id'), (SELECT max(id) FROM ${table}))`, [table]); } await client.query('COMMIT'); } catch (err) { await client.query('ROLLBACK'); throw err; }}export const organisations = [
{ id: 1, name: 'Liffey Estates' },
{ id: 2, name: 'Harbour Lets' },
];
export const buildings = [
{ id: 10, organisationId: 1, name: 'Dublin Offices' },
{ id: 20, organisationId: 1, name: 'Cork Apartments' },
{ id: 30, organisationId: 2, name: 'Galway Studios' },
{ id: 40, organisationId: 2, name: 'Limerick House' },
];
const namedIssues = [
{ id: 101, buildingId: 10, title: 'Lift stuck between floors 2 and 3', priority: 'high', status: 'open', occurredAt: '2026-11-02T09:15:00Z', description: 'The lift stopped between floors with nobody inside. Engineer called.' },
{ id: 102, buildingId: 10, title: 'Dripping tap in the second-floor kitchen', priority: 'low', status: 'closed', occurredAt: '2026-11-05T14:40:00Z', description: 'Worn washer. Tap replaced and floor dried.' },
{ id: 103, buildingId: 20, title: 'Front door lock sticks at entrance 4', priority: 'medium', status: 'open', occurredAt: '2026-11-08T07:05:00Z', description: 'The key turns only after several tries.' },
{ id: 104, buildingId: 20, title: 'Water stain on the ceiling of flat 7', priority: 'high', status: 'investigating', occurredAt: '2026-11-10T11:30:00Z', description: 'Stain about 40 cm wide. Roof drain to be checked.' },
{ id: 105, buildingId: 30, title: 'Boiler lost pressure in plant room', priority: 'critical', status: 'open', occurredAt: '2026-11-11T06:50:00Z', description: 'No heating on the ground floor.' },
{ id: 106, buildingId: 40, title: 'Car park barrier stuck open', priority: 'low', status: 'open', occurredAt: '2026-11-12T16:20:00Z', description: '' },
];
const fillerTitles = [
'Loose handrail on stairs',
'Bins not collected',
'Corridor light not working',
'Radiator cold in room 2',
'Window does not close fully',
'Loose floor tile at entrance',
'Toilet cistern keeps running',
'Blocked sink in kitchen',
];
// 24 extra issues (ids 107-130) alternate between buildings 10 and 20,
// so that lists have enough rows to page, sort and filter.
function fillerIssues() {
const priorities = ['low', 'medium', 'high', 'critical'];
const statuses = ['open', 'investigating', 'closed'];
const issues = [];
for (let i = 0; i < 24; i++) {
issues.push({
id: 107 + i,
buildingId: i % 2 === 0 ? 10 : 20,
title: `${fillerTitles[i % fillerTitles.length]} (#${107 + i})`,
priority: priorities[i % priorities.length],
status: statuses[i % statuses.length],
occurredAt: new Date(Date.UTC(2026, 9, 1 + i, 8 + (i % 9))).toISOString(),
description: '',
});
}
return issues;
}
export const issues = [...namedIssues, ...fillerIssues()];
export const inspections = [
{ id: 201, buildingId: 10, title: 'Q4 lift maintenance inspection', status: 'submitted', findings: 'Service log not signed for October. Emergency phone in lift 2 needs a new battery.' },
{ id: 202, buildingId: 10, title: 'Roof and gutter check, all four sides', status: 'submitted', findings: 'One blocked gutter on the north side.' },
{ id: 203, buildingId: 20, title: 'Door and lock check', status: 'draft', findings: '' },
{ id: 204, buildingId: 30, title: 'Boiler room review', status: 'draft', findings: '' },
];
export async function seed(client) {
await client.query('BEGIN');
try {
await client.query('TRUNCATE inspection_status_changes, inspections, issues, buildings, organisations RESTART IDENTITY CASCADE');
for (const o of organisations) {
await client.query('INSERT INTO organisations (id, name) VALUES ($1, $2)', [o.id, o.name]);
}
for (const s of buildings) {
await client.query('INSERT INTO buildings (id, organisation_id, name) VALUES ($1, $2, $3)', [s.id, s.organisationId, s.name]);
}
for (const e of issues) {
await client.query(
`INSERT INTO issues (id, building_id, title, description, priority, status, occurred_at)
VALUES ($1, $2, $3, $4, $5, $6, $7)`,
[e.id, e.buildingId, e.title, e.description, e.priority, e.status, e.occurredAt],
);
}
for (const a of inspections) {
await client.query(
`INSERT INTO inspections (id, building_id, title, findings, status, submitted_at)
VALUES ($1, $2, $3, $4, $5, CASE WHEN $5 = 'submitted' THEN now() END)`,
[a.id, a.buildingId, a.title, a.findings, a.status],
);
if (a.status === 'submitted') {
await client.query("INSERT INTO inspection_status_changes (inspection_id, from_status, to_status) VALUES ($1, 'draft', 'submitted')", [a.id]);
}
}
for (const table of ['organisations', 'buildings', 'issues', 'inspections']) {
await client.query(`SELECT setval(pg_get_serial_sequence($1, 'id'), (SELECT max(id) FROM ${table}))`, [table]);
}
await client.query('COMMIT');
} catch (err) {
await client.query('ROLLBACK');
throw err;
}
}
npm run db:seed
> caretaker@1.0.0 db:seed
> node --env-file=.env scripts/seed.js
seeded the Caretaker scenario
3. A transaction helper
pool.query may run each statement on a different pooled connection, and a transaction belongs to one connection. Add a helper to src/db.js that borrows one connection and wraps a function in BEGIN/COMMIT:
// Runs fn(client) inside BEGIN/COMMIT on one pooled connection.// If fn throws, the transaction is rolled back and the error is re-thrown.export async function withTransaction(fn) { const client = await pool.connect(); try { await client.query('BEGIN'); const result = await fn(client); await client.query('COMMIT'); return result; } catch (err) { await client.query('ROLLBACK'); throw err; } finally { client.release(); }} export async function query(text, params = []) {
Show the whole src/db.js after this change
import pg from 'pg';import { config } from './config.js'; export const pool = new pg.Pool({ connectionString: config.databaseUrl, max: 10 }); // PostgreSQL error codes (SQLSTATE) that the app turns into user-facing messages.export const PG_ERRORS = { FOREIGN_KEY_VIOLATION: '23503', RESTRICT_VIOLATION: '23001', UNIQUE_VIOLATION: '23505', CHECK_VIOLATION: '23514',}; // Runs fn(client) inside BEGIN/COMMIT on one pooled connection.// If fn throws, the transaction is rolled back and the error is re-thrown.export async function withTransaction(fn) { const client = await pool.connect(); try { await client.query('BEGIN'); const result = await fn(client); await client.query('COMMIT'); return result; } catch (err) { await client.query('ROLLBACK'); throw err; } finally { client.release(); }} export async function query(text, params = []) { const started = Date.now(); const result = await pool.query(text, params); if (config.logSql) { console.log(`SQL ${Date.now() - started}ms ${text.replace(/\s+/g, ' ').trim()} ${JSON.stringify(params)}`); } return result;}import pg from 'pg';
import { config } from './config.js';
export const pool = new pg.Pool({ connectionString: config.databaseUrl, max: 10 });
// PostgreSQL error codes (SQLSTATE) that the app turns into user-facing messages.
export const PG_ERRORS = {
FOREIGN_KEY_VIOLATION: '23503',
RESTRICT_VIOLATION: '23001',
UNIQUE_VIOLATION: '23505',
CHECK_VIOLATION: '23514',
};
// Runs fn(client) inside BEGIN/COMMIT on one pooled connection.
// If fn throws, the transaction is rolled back and the error is re-thrown.
export async function withTransaction(fn) {
const client = await pool.connect();
try {
await client.query('BEGIN');
const result = await fn(client);
await client.query('COMMIT');
return result;
} catch (err) {
await client.query('ROLLBACK');
throw err;
} finally {
client.release();
}
}
export async function query(text, params = []) {
const started = Date.now();
const result = await pool.query(text, params);
if (config.logSql) {
console.log(`SQL ${Date.now() - started}ms ${text.replace(/\s+/g, ' ').trim()} ${JSON.stringify(params)}`);
}
return result;
}
client.release() in finally returns the connection to the pool whatever happens. Forgetting it is a classic bug: after max (10) leaks, every request waits forever for a free connection.
4. The inspection model and its state machine
Create src/models/inspections.js:
import { query, withTransaction } from '../db.js'; // The workflow. Each action moves an inspection from exactly one status to another.export const INSPECTION_TRANSITIONS = { submit: { from: 'draft', to: 'submitted' }, approve: { from: 'submitted', to: 'approved' }, return: { from: 'submitted', to: 'draft' },}; const INSPECTION_COLUMNS = ` a.id, a.building_id, s.name AS building_name, s.organisation_id, a.title, a.findings, a.status, a.submitted_at, a.approved_at, a.created_at, a.updated_at`; export async function listInspections({ status = null } = {}) { const params = []; let whereSql = ''; if (status) { params.push(status); whereSql = 'WHERE a.status = $1'; } const { rows } = await query( `SELECT ${INSPECTION_COLUMNS} FROM inspections a JOIN buildings s ON s.id = a.building_id ${whereSql} ORDER BY a.updated_at DESC, a.id DESC`, params, ); return rows;} export async function findInspection(id) { const { rows } = await query(`SELECT ${INSPECTION_COLUMNS} FROM inspections a JOIN buildings s ON s.id = a.building_id WHERE a.id = $1`, [id]); return rows[0] ?? null;} export async function listInspectionHistory(inspectionId) { const { rows } = await query( 'SELECT from_status, to_status, changed_at FROM inspection_status_changes WHERE inspection_id = $1 ORDER BY changed_at, id', [inspectionId], ); return rows;} export async function createInspection({ building_id, title, findings }) { const { rows } = await query( 'INSERT INTO inspections (building_id, title, findings) VALUES ($1, $2, $3) RETURNING id', [building_id, title, findings], ); return rows[0];} // Only drafts can be edited. Returns false if the inspection is not (or no longer) a draft.export async function updateDraftInspection(id, { title, findings }) { const { rowCount } = await query( "UPDATE inspections SET title = $2, findings = $3, updated_at = now() WHERE id = $1 AND status = 'draft'", [id, title, findings], ); return rowCount === 1;} // Applies a transition atomically. Returns false if the inspection was not in the expected status.export async function transitionInspection(id, action) { const transition = INSPECTION_TRANSITIONS[action]; if (!transition) { throw new Error(`Unknown inspection action ${action}`); } return withTransaction(async (client) => { const { rowCount } = await client.query( `UPDATE inspections SET status = $3, updated_at = now(), submitted_at = CASE WHEN $3 = 'submitted' THEN now() ELSE submitted_at END, approved_at = CASE WHEN $3 = 'approved' THEN now() ELSE approved_at END WHERE id = $1 AND status = $2`, [id, transition.from, transition.to], ); if (rowCount === 0) { return false; } await client.query( 'INSERT INTO inspection_status_changes (inspection_id, from_status, to_status) VALUES ($1, $2, $3)', [id, transition.from, transition.to], ); return true; });}The heart of the lesson is transitionInspection:
WHERE id = $1 AND status = $2makes the check part of the update. PostgreSQL locks the row while it updates it. If two transactions try at the same moment, the second waits for the first to finish, then re-checks theWHEREagainst the new row, findsstatus = 'approved', and updates nothing.rowCounttells us who won.withTransactionmakes the status change and the history row one unit. If theINSERTfailed, theUPDATEwould be rolled back too.updateDraftInspectionuses the same trick:AND status = 'draft'means an inspection approved a millisecond ago cannot be edited by a request that loaded it as a draft.
5. The inspections router
Create src/routes/inspections.js:
import express from 'express';import { listInspections, findInspection, listInspectionHistory, createInspection, updateDraftInspection, transitionInspection, INSPECTION_TRANSITIONS } from '../models/inspections.js';import { listBuildings } from '../models/buildings.js';import { PG_ERRORS } from '../db.js';import { parseId } from '../lib/ids.js';import { cleanText } from '../lib/validation.js'; export const inspectionsRouter = express.Router(); const INSPECTION_STATUSES = ['draft', 'submitted', 'approved']; function validateInspection(input, { requireBuilding }) { const errors = {}; const title = cleanText(input.title, { min: 3, max: 200 }); const findings = cleanText(input.findings, { max: 5000 }); const buildingId = parseId(input.building_id); if (!title.ok) errors.title = 'Title must be between 3 and 200 characters.'; if (!findings.ok) errors.findings = 'Findings must be at most 5000 characters.'; if (requireBuilding && buildingId === null) errors.building_id = 'Choose a building.'; return { errors, values: { title: title.text, findings: findings.text, building_id: buildingId } };} async function renderInspectionForm(res, status, { inspection = null, values = {}, errors = {} } = {}) { res.status(status).render('inspections/form', { title: inspection ? `Edit inspection #${inspection.id}` : 'New inspection', action: inspection ? `/inspections/${inspection.id}/edit` : '/inspections', inspection, values, errors, buildings: inspection ? [] : await listBuildings(), });} async function renderInspectionPage(res, status, inspection, error = null) { const history = await listInspectionHistory(inspection.id); res.status(status).render('inspections/show', { title: inspection.title, inspection, history, error });} async function loadInspection(req, res) { const id = parseId(req.params.id); const inspection = id === null ? null : await findInspection(id); if (!inspection) { res.status(404).render('not-found', { title: 'Not found', path: req.originalUrl }); return null; } return inspection;} inspectionsRouter.get('/', async (req, res) => { const status = INSPECTION_STATUSES.includes(req.query.status) ? req.query.status : null; res.render('inspections/index', { title: 'Inspections', inspections: await listInspections({ status }), status, statuses: INSPECTION_STATUSES });}); inspectionsRouter.get('/new', async (req, res) => { await renderInspectionForm(res, 200);}); inspectionsRouter.post('/', async (req, res) => { const { errors, values } = validateInspection(req.body ?? {}, { requireBuilding: true }); if (Object.keys(errors).length > 0) { return renderInspectionForm(res, 400, { values, errors }); } try { const created = await createInspection(values); res.redirect(303, `/inspections/${created.id}`); } catch (err) { if (err.code === PG_ERRORS.FOREIGN_KEY_VIOLATION) { return renderInspectionForm(res, 400, { values, errors: { building_id: 'Choose a building.' } }); } throw err; }}); inspectionsRouter.get('/:id', async (req, res) => { const inspection = await loadInspection(req, res); if (!inspection) return; await renderInspectionPage(res, 200, inspection);}); inspectionsRouter.get('/:id/edit', async (req, res) => { const inspection = await loadInspection(req, res); if (!inspection) return; if (inspection.status !== 'draft') { return renderInspectionPage(res, 409, inspection, 'Only draft inspections can be edited.'); } await renderInspectionForm(res, 200, { inspection, values: inspection });}); inspectionsRouter.post('/:id/edit', async (req, res) => { const inspection = await loadInspection(req, res); if (!inspection) return; const { errors, values } = validateInspection(req.body ?? {}, { requireBuilding: false }); if (Object.keys(errors).length > 0) { return renderInspectionForm(res, 400, { inspection, values, errors }); } const updated = await updateDraftInspection(inspection.id, values); if (!updated) { return renderInspectionPage(res, 409, inspection, 'Only draft inspections can be edited.'); } res.redirect(303, `/inspections/${inspection.id}`);}); // POST /inspections/:id/submit, /approve and /return share one handler.inspectionsRouter.post('/:id/:action', async (req, res, next) => { if (!Object.hasOwn(INSPECTION_TRANSITIONS, req.params.action)) { return next(); } const inspection = await loadInspection(req, res); if (!inspection) return; const changed = await transitionInspection(inspection.id, req.params.action); if (!changed) { const fresh = await findInspection(inspection.id); return renderInspectionPage(res, 409, fresh, `This inspection is ${fresh.status}; it cannot be ${req.params.action === 'return' ? 'returned' : `${req.params.action}d`} now.`); } res.redirect(303, `/inspections/${inspection.id}`);});- The building is chosen only when an inspection is created. An inspection cannot move to another building;
validateInspectionignoresbuilding_idwhen editing. POST /:id/:actionhandles the three transitions. Unknown actions callnext(), which falls through to the 404 handler, soPOST /inspections/201/deleteis simply "not found".- On a refused transition we reload the inspection (
fresh) so the page shows its current status, which another user may just have changed.
Mount the router and add a navigation link:
import { buildingsRouter } from './routes/buildings.js';import { inspectionsRouter } from './routes/inspections.js';
app.use('/buildings', buildingsRouter);app.use('/inspections', inspectionsRouter);
Show the whole src/app.js after this change
import express from 'express';import path from 'node:path';import { issuesRouter } from './routes/issues.js';import { organisationsRouter } from './routes/organisations.js';import { buildingsRouter } from './routes/buildings.js';import { inspectionsRouter } from './routes/inspections.js'; export const app = express(); app.set('view engine', 'ejs');app.set('views', path.join(import.meta.dirname, '..', 'views'));app.locals.formatDate = (value) => new Date(value).toLocaleString('en-IE', { dateStyle: 'medium', timeStyle: 'short', timeZone: 'UTC' }); app.use((req, res, next) => { if (process.env.NODE_ENV === 'test') { return next(); } const started = Date.now(); res.on('finish', () => { console.log(`${req.method} ${req.originalUrl} -> ${res.statusCode} (${Date.now() - started} ms)`); }); next();}); app.use(express.static(path.join(import.meta.dirname, '..', 'public')));app.use(express.urlencoded({ extended: false })); app.get('/', (req, res) => { res.redirect('/issues');}); app.use('/issues', issuesRouter);app.use('/organisations', organisationsRouter);app.use('/buildings', buildingsRouter);app.use('/inspections', inspectionsRouter); app.use((req, res) => { res.status(404).render('not-found', { title: 'Not found', path: req.originalUrl });}); app.use((err, req, res, next) => { const status = err.status ?? 500; if (status >= 500) { console.error(err); } const message = err.expose ? err.message : 'Something went wrong'; res.status(status).render('error', { title: 'Error', status, message });});import express from 'express';
import path from 'node:path';
import { issuesRouter } from './routes/issues.js';
import { organisationsRouter } from './routes/organisations.js';
import { buildingsRouter } from './routes/buildings.js';
import { inspectionsRouter } from './routes/inspections.js';
export const app = express();
app.set('view engine', 'ejs');
app.set('views', path.join(import.meta.dirname, '..', 'views'));
app.locals.formatDate = (value) => new Date(value).toLocaleString('en-IE', { dateStyle: 'medium', timeStyle: 'short', timeZone: 'UTC' });
app.use((req, res, next) => {
if (process.env.NODE_ENV === 'test') {
return next();
}
const started = Date.now();
res.on('finish', () => {
console.log(`${req.method} ${req.originalUrl} -> ${res.statusCode} (${Date.now() - started} ms)`);
});
next();
});
app.use(express.static(path.join(import.meta.dirname, '..', 'public')));
app.use(express.urlencoded({ extended: false }));
app.get('/', (req, res) => {
res.redirect('/issues');
});
app.use('/issues', issuesRouter);
app.use('/organisations', organisationsRouter);
app.use('/buildings', buildingsRouter);
app.use('/inspections', inspectionsRouter);
app.use((req, res) => {
res.status(404).render('not-found', { title: 'Not found', path: req.originalUrl });
});
app.use((err, req, res, next) => {
const status = err.status ?? 500;
if (status >= 500) {
console.error(err);
}
const message = err.expose ? err.message : 'Something went wrong';
res.status(status).render('error', { title: 'Error', status, message });
});
<a href="/issues">Issues</a> <a href="/inspections">Inspections</a>
Show the whole views/partials/nav.ejs after this change
<header class="site-header"> <div class="container header-inner"> <a class="brand" href="/">Caretaker</a> <nav class="main-nav" aria-label="Main"> <a href="/issues">Issues</a> <a href="/inspections">Inspections</a> <a href="/organisations">Organisations</a> </nav> </div></header><header class="site-header">
<div class="container header-inner">
<a class="brand" href="/">Caretaker</a>
<nav class="main-nav" aria-label="Main">
<a href="/issues">Issues</a>
<a href="/inspections">Inspections</a>
<a href="/organisations">Organisations</a>
</nav>
</div>
</header>
6. Views
<%- include('../partials/head') %><div class="page-header"> <h1>Inspections</h1> <a class="btn btn-primary" href="/inspections/new">New inspection</a></div><form method="get" action="/inspections" class="filters"> <label>Status <select name="status"> <option value="">Any</option> <% for (const s of statuses) { %><option value="<%= s %>"<%= status === s ? ' selected' : '' %>><%= s %></option><% } %> </select> </label> <button type="submit" class="btn btn-small">Apply</button></form><% if (inspections.length === 0) { %> <p class="empty">No inspections.</p><% } else { %> <table class="data"> <thead><tr><th>Title</th><th>Building</th><th>Status</th><th>Last change</th></tr></thead> <tbody> <% for (const inspection of inspections) { %> <tr> <td><a href="/inspections/<%= inspection.id %>"><%= inspection.title %></a></td> <td><%= inspection.building_name %></td> <td><span class="badge status-<%= inspection.status %>"><%= inspection.status %></span></td> <td><%= formatDate(inspection.updated_at) %></td> </tr> <% } %> </tbody> </table><% } %><%- include('../partials/foot') %><%- include('../partials/head') %><p class="breadcrumbs"><a href="/inspections">Inspections</a> / #<%= inspection.id %></p><div class="page-header"> <h1><%= inspection.title %></h1> <div class="actions"> <% if (inspection.status === 'draft') { %> <a class="btn" href="/inspections/<%= inspection.id %>/edit">Edit</a> <form method="post" action="/inspections/<%= inspection.id %>/submit"><button type="submit" class="btn btn-primary">Submit for approval</button></form> <% } %> <% if (inspection.status === 'submitted') { %> <form method="post" action="/inspections/<%= inspection.id %>/return"><button type="submit" class="btn">Return to draft</button></form> <form method="post" action="/inspections/<%= inspection.id %>/approve" data-confirm="Approve this inspection? Approved inspections cannot be changed."><button type="submit" class="btn btn-primary">Approve</button></form> <% } %> </div></div><% if (error) { %> <div class="flash flash-error" role="alert"><%= error %></div><% } %><dl class="details"> <dt>Building</dt><dd><a href="/buildings/<%= inspection.building_id %>"><%= inspection.building_name %></a></dd> <dt>Status</dt><dd><span class="badge status-<%= inspection.status %>"><%= inspection.status %></span></dd> <% if (inspection.submitted_at) { %><dt>Submitted</dt><dd><%= formatDate(inspection.submitted_at) %> UTC</dd><% } %> <% if (inspection.approved_at) { %><dt>Approved</dt><dd><%= formatDate(inspection.approved_at) %> UTC</dd><% } %></dl><h2>Findings</h2><% if (inspection.findings) { %><p class="prose"><%= inspection.findings %></p><% } else { %><p class="empty">No findings recorded yet.</p><% } %><h2>History</h2><% if (history.length === 0) { %> <p class="muted">No status changes yet.</p><% } else { %> <table class="data"> <thead><tr><th>When (UTC)</th><th>Change</th></tr></thead> <tbody> <% for (const h of history) { %> <tr><td><%= formatDate(h.changed_at) %></td><td><%= h.from_status %> → <%= h.to_status %></td></tr> <% } %> </tbody> </table><% } %><%- include('../partials/foot') %><%- include('../partials/head') %><h1><%= title %></h1><form method="post" action="<%= action %>" class="form" novalidate> <% if (!inspection) { %> <div class="field<%= errors.building_id ? ' has-error' : '' %>"> <label for="building_id">Building</label> <select id="building_id" name="building_id"> <option value="">Choose…</option> <% for (const building of buildings) { %> <option value="<%= building.id %>"<%= values.building_id === building.id ? ' selected' : '' %>><%= building.organisation_name %> · <%= building.name %></option> <% } %> </select> <% if (errors.building_id) { %><p class="field-error"><%= errors.building_id %></p><% } %> </div> <% } %> <div class="field<%= errors.title ? ' has-error' : '' %>"> <label for="title">Title</label> <input id="title" name="title" value="<%= values.title ?? '' %>" maxlength="200"> <% if (errors.title) { %><p class="field-error"><%= errors.title %></p><% } %> </div> <div class="field<%= errors.findings ? ' has-error' : '' %>"> <label for="findings">Findings</label> <textarea id="findings" name="findings" maxlength="5000"><%= values.findings ?? '' %></textarea> <% if (errors.findings) { %><p class="field-error"><%= errors.findings %></p><% } %> </div> <div class="form-actions"> <button type="submit" class="btn btn-primary"><%= inspection ? 'Save draft' : 'Create draft' %></button> <a class="btn" href="<%= inspection ? `/inspections/${inspection.id}` : '/inspections' %>">Cancel</a> </div></form><%- include('../partials/foot') %>The buttons on the inspection page only appear when the transition is possible. That is for usability. The server enforces the rule on every request, buttons or not.
Run and inspect
npm run dev
> caretaker@1.0.0 dev
> node --env-file=.env --watch src/server.js
Caretaker listening on http://localhost:3000

Approve inspection 201 with a form post, then try again:
curl -si -X POST http://localhost:3000/inspections/201/approve | head -1
HTTP/1.1 303 See Other
curl -si -X POST http://localhost:3000/inspections/201/approve | head -1
HTTP/1.1 409 Conflict
docker compose exec db psql -U caretaker caretaker, then paste the SQL.SELECT a.id, a.status, a.approved_at IS NOT NULL AS has_approved_at, h.from_status, h.to_statusFROM inspections a JOIN inspection_status_changes h ON h.inspection_id = a.idWHERE a.id = 201 ORDER BY h.id;
id | status | has_approved_at | from_status | to_status
-----+----------+-----------------+-------------+-----------
201 | approved | t | draft | submitted
201 | approved | t | submitted | approved
(2 rows)One submission and exactly one approval in the history.
Experiment
Now the race. Inspection 202 is submitted. We send ten approve requests at the same time. The & runs each curl in the background; sort | uniq -c waits for all ten answers and counts each status code:
submitted → approved?for i in $(seq 10); do curl -s -o /dev/null -w "%{http_code}\n" -X POST http://localhost:3000/inspections/202/approve & done | sort | uniq -c
1 303
9 409
docker compose exec db psql -U caretaker caretaker, then paste the SQL.SELECT from_status, to_status, count(*)FROM inspection_status_changesWHERE inspection_id = 202GROUP BY from_status, to_statusORDER BY 1;
from_status | to_status | count
-------------+-----------+-------
draft | submitted | 1
submitted | approved | 1
(2 rows)Reveal What happened
Exactly one request won. Each UPDATE ... WHERE id = $1 AND status = 'submitted' locked the row; the others waited, re-checked the condition against the committed row, matched nothing, and the route answered 409. Because the history INSERT is in the same transaction as the winning UPDATE, there is exactly one history row per real change. A version that first ran SELECT status, checked it in JavaScript, then ran UPDATE ... WHERE id = $1 would sometimes approve twice and write two history rows.
Checkpoint
import { test, before, after } from 'node:test';import assert from 'node:assert/strict';import request from 'supertest';import { app } from '../src/app.js';import { pool } from '../src/db.js';import { resetDatabase } from './helpers.js'; before(resetDatabase);after(() => pool.end()); async function history(inspectionId) { const { rows } = await pool.query('SELECT from_status, to_status FROM inspection_status_changes WHERE inspection_id = $1 ORDER BY id', [inspectionId]); return rows.map((r) => `${r.from_status}->${r.to_status}`);} test('create a draft, edit it, submit it, approve it', async () => { const created = await request(app).post('/inspections').type('form').send({ building_id: '20', title: 'Stairwell lighting check', findings: '' }); assert.equal(created.status, 303); const url = created.headers.location; assert.equal((await request(app).post(`${url}/edit`).type('form').send({ title: 'Stairwell lighting check', findings: 'All bulbs working.' })).status, 303); assert.equal((await request(app).post(`${url}/submit`)).status, 303); assert.equal((await request(app).post(`${url}/approve`)).status, 303); const id = Number(url.split('/').pop()); assert.deepEqual(await history(id), ['draft->submitted', 'submitted->approved']); const page = await request(app).get(url); assert.match(page.text, /All bulbs working/); assert.match(page.text, /badge status-approved/);}); test('invalid transitions are refused with 409 and change nothing', async () => { assert.equal((await request(app).post('/inspections/203/approve')).status, 409); assert.equal((await request(app).post('/inspections/203/return')).status, 409); assert.deepEqual(await history(203), []);}); test('only drafts can be edited', async () => { const res = await request(app).post('/inspections/201/edit').type('form').send({ title: 'Changed after submission', findings: '' }); assert.equal(res.status, 409); const { rows } = await pool.query('SELECT title FROM inspections WHERE id = 201'); assert.equal(rows[0].title, 'Q4 lift maintenance inspection');}); test('returning a submitted inspection makes it editable again', async () => { assert.equal((await request(app).post('/inspections/202/return')).status, 303); assert.equal((await request(app).get('/inspections/202/edit')).status, 200);}); test('concurrent approvals: exactly one wins', async () => { const results = await Promise.all(Array.from({ length: 8 }, () => request(app).post('/inspections/201/approve'))); assert.deepEqual(results.map((r) => r.status).sort(), [303, 409, 409, 409, 409, 409, 409, 409]); assert.deepEqual(await history(201), ['draft->submitted', 'submitted->approved']);}); test('unknown actions are 404', async () => { assert.equal((await request(app).post('/inspections/201/delete')).status, 404);});npm test
> caretaker@1.0.0 test
> node --env-file=.env.test --test --test-concurrency=1 --test-reporter=spec "test/**/*.test.js"
✔ a building can be created inside an organisation (81.016583ms)
✔ a duplicate building name in the same organisation is a field error (3.620125ms)
✔ the same building name is allowed in another organisation (7.657542ms)
✔ a building with issues cannot be deleted (22.665375ms)
✔ an empty building can be deleted (6.951125ms)
✔ an organisation with buildings cannot be deleted, an empty one can (13.695792ms)
✔ create a draft, edit it, submit it, approve it (79.072792ms)
✔ invalid transitions are refused with 409 and change nothing (7.953625ms)
✔ only drafts can be edited (2.891584ms)
✔ returning a submitted inspection makes it editable again (5.697709ms)
✔ concurrent approvals: exactly one wins (19.701334ms)
✔ unknown actions are 404 (1.221916ms)
✔ the list pages 10 at a time and reports the total (68.272459ms)
✔ pages do not overlap (9.328ms)
✔ filters combine with AND (3.537208ms)
✔ sorting by priority puts critical first when descending (2.844583ms)
✔ unknown sort keys and SQL in the query string are ignored (17.208209ms)
✔ GET /issues lists issues from the database (74.503166ms)
✔ GET /issues/101 shows one issue with its building (3.875333ms)
✔ GET /issues/:id answers 404 for unknown or malformed ids (5.681625ms)
✔ POST /issues re-renders the form with errors (6.266375ms)
✔ POST /issues stores the issue and redirects to it (5.712333ms)
✔ POST /issues with a building that does not exist is a form error, not a 500 (9.424208ms)
✔ the stored row has the cleaned values and ignores a client-sent status (3.593417ms)
✔ an issue time in the future is rejected (1.945541ms)
✔ GET /issues/101/edit shows the current values (2.156666ms)
✔ POST /issues/:id/edit changes the status and updated_at (2.706416ms)
✔ POST /issues/:id/delete removes the issue (3.784208ms)
✔ GET /organisations lists organisations with building counts (59.905041ms)
✔ GET /organisations/1 shows its buildings, not other organisations' buildings (3.920083ms)
✔ POST /organisations validates and creates (10.784541ms)
✔ POST /organisations/:id/edit renames the organisation (5.375708ms)
✔ unknown organisations are 404 (4.545916ms)
ℹ tests 33
ℹ suites 0
ℹ pass 33
Show 5 more lines
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 1047.878625
git add -A
git commit -m "Inspections with a workflow and transactions"
[main 4113499] Inspections with a workflow and transactions
11 files changed, 426 insertions(+), 2 deletions(-)
create mode 100644 migrations/002_create_inspections.sql
create mode 100644 src/models/inspections.js
create mode 100644 src/routes/inspections.js
create mode 100644 test/inspections.test.js
create mode 100644 views/inspections/form.ejs
create mode 100644 views/inspections/index.ejs
create mode 100644 views/inspections/show.ejs
Symptom Requests hang after a few transitions
A code path borrowed a client with pool.connect() and never released it. Use withTransaction, which releases in finally.
Symptom could not determine data type of parameter $3
PostgreSQL could not infer a parameter's type from where it is used. Here $3 is compared with status first, which fixes its type as text. If you reorder the SQL, add a cast: $3::text.
Recap and next step
Inspections follow a state machine defined in one object (INSPECTION_TRANSITIONS). A conditional UPDATE ... WHERE status = $expected checks and changes atomically; rowCount reports whether the transition happened. withTransaction groups the update with its history row. You saw ten simultaneous requests produce exactly one approval.
One more page completes the CRUD application: a dashboard that summarises everything. After that, we add users.
Open the checkpoint files for lesson 3.5 (separate page; only files from this lesson and earlier)