Caretaker Express · PostgreSQL · Cedar

Module 3 · Build real CRUD features

3.1 Routers, and organisations you can create and edit

Split routes into Express routers before app.js becomes unreadable, then build list, view, create and update for organisations with a shared form.

≈ 75 min 18 steps 345 lines of code Replay verified

Starting point

All routes live in src/app.js, and only issues have pages. Organisations and buildings exist in the database but nowhere in the UI.

Outcome

Text
src/├── app.js                  (settings, middleware, mounting, error handling)├── lib/ids.js              (new: parseId)├── models/organisations.js (new)├── models/buildings.js         (+ listBuildingsForOrganisation)└── routes/    ├── issues.js           (moved from app.js)    └── organisations.js    (new)views/organisations/  index.ejs  show.ejs  form.ejstest/organisations.test.js

/organisations lists both organisations with their building counts. You can open one, see its buildings, create a new organisation and rename it.

The problem

src/app.js is already 110 lines, and we are about to add organisations, buildings and inspections, each with five to eight routes. One file would grow past 500 lines, with every resource's validation and helpers mixed together. Express has a built-in answer: a router is a mini-application with its own routes, which you mount at a path prefix.

Build it

1. Move parseId to a shared module

Every resource needs to validate IDs. Create src/lib/ids.js with the function from app.js:

Create filesrc/lib/ids.jsJavaScript
const MAX_INTEGER = 2147483647; // Returns a positive integer that fits a PostgreSQL integer column, or null.export function parseId(value) {  if (typeof value !== 'string' || !/^[1-9][0-9]{0,9}$/.test(value)) {    return null;  }  const id = Number(value);  return id <= MAX_INTEGER ? id : null;}

2. An issues router

Create src/routes/issues.js. The code is the issue code from app.js, with two mechanical changes: routes are registered on issuesRouter instead of app, and their paths drop the /issues prefix, because the router is mounted at /issues:

Create filesrc/routes/issues.jsJavaScript
import express from 'express';import { listIssues, findIssue, createIssue } from '../models/issues.js';import { listBuildings } from '../models/buildings.js';import { PG_ERRORS } from '../db.js';import { parseId } from '../lib/ids.js'; export const issuesRouter = express.Router(); const PRIORITIES = ['low', 'medium', 'high', 'critical']; function validateIssue(input) {  const errors = {};  const title = typeof input.title === 'string' ? input.title.trim() : '';  const description = typeof input.description === 'string' ? input.description.trim() : '';  const buildingId = parseId(input.building_id);  if (title.length < 3 || title.length > 200) {    errors.title = 'Title must be between 3 and 200 characters.';  }  if (description.length > 2000) {    errors.description = 'Description must be at most 2000 characters.';  }  if (!PRIORITIES.includes(input.priority)) {    errors.priority = `Priority must be one of: ${PRIORITIES.join(', ')}.`;  }  if (buildingId === null) {    errors.building_id = 'Choose a building.';  }  return { errors, values: { title, description, priority: input.priority, building_id: buildingId } };} async function renderIssueForm(res, status, { values = {}, errors = {} } = {}) {  const buildings = await listBuildings();  res.status(status).render('issues/new', { title: 'Report an issue', values, errors, priorities: PRIORITIES, buildings });} issuesRouter.get('/', async (req, res) => {  const issues = await listIssues();  res.render('issues/index', { title: 'Maintenance issues', issues });}); issuesRouter.get('/new', async (req, res) => {  await renderIssueForm(res, 200);}); issuesRouter.post('/', async (req, res) => {  const { errors, values } = validateIssue(req.body ?? {});  if (Object.keys(errors).length > 0) {    return renderIssueForm(res, 400, { values, errors });  }  let issue;  try {    issue = await createIssue(values);  } catch (err) {    if (err.code === PG_ERRORS.FOREIGN_KEY_VIOLATION) {      return renderIssueForm(res, 400, { values, errors: { building_id: 'Choose a building.' } });    }    throw err;  }  res.redirect(303, `/issues/${issue.id}`);}); issuesRouter.get('/:id', async (req, res) => {  const id = parseId(req.params.id);  const issue = id === null ? null : await findIssue(id);  if (!issue) {    return res.status(404).render('not-found', { title: 'Not found', path: req.originalUrl });  }  res.render('issues/show', { title: issue.title, issue });});

One subtle change: inside a router req.path is relative to the mount point (/101), so the 404 page now uses req.originalUrl (/issues/101).

3. Data access for organisations

Create src/models/organisations.js:

Create filesrc/models/organisations.jsJavaScript
import { query } from '../db.js'; export async function listOrganisations() {  const { rows } = await query(    `SELECT o.id, o.name, count(s.id)::int AS building_count     FROM organisations o     LEFT JOIN buildings s ON s.organisation_id = o.id     GROUP BY o.id     ORDER BY o.name`,  );  return rows;} export async function findOrganisation(id) {  const { rows } = await query('SELECT id, name, created_at, updated_at FROM organisations WHERE id = $1', [id]);  return rows[0] ?? null;} export async function createOrganisation({ name }) {  const { rows } = await query('INSERT INTO organisations (name) VALUES ($1) RETURNING id', [name]);  return rows[0];} export async function updateOrganisation(id, { name }) {  const { rows } = await query(    'UPDATE organisations SET name = $2, updated_at = now() WHERE id = $1 RETURNING id',    [id, name],  );  return rows[0] ?? null;}
  • count(s.id)::int: PostgreSQL's count returns a bigint, which can exceed JavaScript's safe integer range, so pg returns it as a string ("2"). The ::int cast converts it in SQL, where we know the number is small.
  • UPDATE ... RETURNING id returns no row when the ID does not exist, so updateOrganisation returns null and the route can answer 404.
  • We set updated_at = now() ourselves. PostgreSQL does not update it automatically.

The organisation page lists its buildings. Add a function to src/models/buildings.js:

Editsrc/models/buildings.jsJavaScript
Remove the lines marked − and add the lines marked +. Unmarked lines stay as they are; they show you where the change goes.
     ORDER BY o.name, s.name`,  );  return rows;} export async function listBuildingsForOrganisation(organisationId) {  const { rows } = await query(    `SELECT s.id, s.name, count(e.id)::int AS issue_count     FROM buildings s     LEFT JOIN issues e ON e.building_id = s.id     WHERE s.organisation_id = $1     GROUP BY s.id     ORDER BY s.name`,    [organisationId],  );  return rows;}
Show the whole src/models/buildings.js after this change
import { query } from '../db.js'; export async function listBuildings() {  const { rows } = await query(    `SELECT s.id, s.name, s.organisation_id, o.name AS organisation_name     FROM buildings s     JOIN organisations o ON o.id = s.organisation_id     ORDER BY o.name, s.name`,  );  return rows;} export async function listBuildingsForOrganisation(organisationId) {  const { rows } = await query(    `SELECT s.id, s.name, count(e.id)::int AS issue_count     FROM buildings s     LEFT JOIN issues e ON e.building_id = s.id     WHERE s.organisation_id = $1     GROUP BY s.id     ORDER BY s.name`,    [organisationId],  );  return rows;}

4. The organisations router

Create src/routes/organisations.js:

Create filesrc/routes/organisations.jsJavaScript
import express from 'express';import { listOrganisations, findOrganisation, createOrganisation, updateOrganisation } from '../models/organisations.js';import { listBuildingsForOrganisation } from '../models/buildings.js';import { parseId } from '../lib/ids.js'; export const organisationsRouter = express.Router(); function validateOrganisation(input) {  const errors = {};  const name = typeof input.name === 'string' ? input.name.trim() : '';  if (name.length < 2 || name.length > 100) {    errors.name = 'Name must be between 2 and 100 characters.';  }  return { errors, values: { name } };} function renderForm(res, status, { organisation = null, values = {}, errors = {} }) {  res.status(status).render('organisations/form', {    title: organisation ? `Edit ${organisation.name}` : 'New organisation',    action: organisation ? `/organisations/${organisation.id}/edit` : '/organisations',    organisation,    values,    errors,  });} // Loads the organisation named by :id, or answers 404. Returns null when it answered.async function loadOrganisation(req, res) {  const id = parseId(req.params.id);  const organisation = id === null ? null : await findOrganisation(id);  if (!organisation) {    res.status(404).render('not-found', { title: 'Not found', path: req.originalUrl });    return null;  }  return organisation;} organisationsRouter.get('/', async (req, res) => {  res.render('organisations/index', { title: 'Organisations', organisations: await listOrganisations() });}); organisationsRouter.get('/new', (req, res) => {  renderForm(res, 200, {});}); organisationsRouter.post('/', async (req, res) => {  const { errors, values } = validateOrganisation(req.body ?? {});  if (Object.keys(errors).length > 0) {    return renderForm(res, 400, { values, errors });  }  const created = await createOrganisation(values);  res.redirect(303, `/organisations/${created.id}`);}); organisationsRouter.get('/:id', async (req, res) => {  const organisation = await loadOrganisation(req, res);  if (!organisation) return;  const buildings = await listBuildingsForOrganisation(organisation.id);  res.render('organisations/show', { title: organisation.name, organisation, buildings });}); organisationsRouter.get('/:id/edit', async (req, res) => {  const organisation = await loadOrganisation(req, res);  if (!organisation) return;  renderForm(res, 200, { organisation, values: organisation });}); organisationsRouter.post('/:id/edit', async (req, res) => {  const organisation = await loadOrganisation(req, res);  if (!organisation) return;  const { errors, values } = validateOrganisation(req.body ?? {});  if (Object.keys(errors).length > 0) {    return renderForm(res, 400, { organisation, values, errors });  }  await updateOrganisation(organisation.id, values);  res.redirect(303, `/organisations/${organisation.id}`);});

Notes on the design:

  • One form template for create and edit. renderForm sets the heading and the form's action. The edit form starts with the current values.
  • loadOrganisation is the "find it or 404" step that every /:id route needs. It returns null after it has answered, and the route stops with if (!organisation) return;. Remember this function: in Module 5 the same place decides whether you may see the organisation.
  • Edit uses POST /organisations/:id/edit. HTML forms can only send GET and POST, so we use a distinct URL instead of PUT. The same goes for delete in the next lesson.

5. Views

Create fileviews/organisations/index.ejsEJS
<%- include('../partials/head') %><div class="page-header">  <h1>Organisations</h1>  <a class="btn btn-primary" href="/organisations/new">New organisation</a></div><table class="data">  <thead><tr><th>Name</th><th>Buildings</th></tr></thead>  <tbody>    <% for (const organisation of organisations) { %>      <tr>        <td><a href="/organisations/<%= organisation.id %>"><%= organisation.name %></a></td>        <td><%= organisation.building_count %></td>      </tr>    <% } %>  </tbody></table><%- include('../partials/foot') %>
Create fileviews/organisations/show.ejsEJS
<%- include('../partials/head') %><p class="breadcrumbs"><a href="/organisations">Organisations</a> / #<%= organisation.id %></p><div class="page-header">  <h1><%= organisation.name %></h1>  <div class="actions">    <a class="btn" href="/organisations/<%= organisation.id %>/edit">Edit</a>  </div></div> <h2>Buildings</h2><% if (buildings.length === 0) { %>  <p class="empty">This organisation has no buildings yet.</p><% } else { %>  <table class="data">    <thead><tr><th>Building</th><th>Issues</th></tr></thead>    <tbody>      <% for (const building of buildings) { %>        <tr><td><%= building.name %></td><td><%= building.issue_count %></td></tr>      <% } %>    </tbody>  </table><% } %><%- include('../partials/foot') %>
Create fileviews/organisations/form.ejsEJS
<%- include('../partials/head') %><h1><%= title %></h1><form method="post" action="<%= action %>" class="form" novalidate>  <div class="field<%= errors.name ? ' has-error' : '' %>">    <label for="name">Name</label>    <input id="name" name="name" value="<%= values.name ?? '' %>" maxlength="100" required>    <% if (errors.name) { %><p class="field-error"><%= errors.name %></p><% } %>  </div>  <div class="form-actions">    <button type="submit" class="btn btn-primary"><%= organisation ? 'Save changes' : 'Create organisation' %></button>    <a class="btn" href="<%= organisation ? `/organisations/${organisation.id}` : '/organisations' %>">Cancel</a>  </div></form><%- include('../partials/foot') %>

Add the link to the navigation:

Editviews/partials/nav.ejsEJS
Remove the lines marked − and add the lines marked +. Unmarked lines stay as they are; they show you where the change goes.
      <a href="/issues">Issues</a>      <a href="/organisations">Organisations</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="/organisations">Organisations</a>    </nav>  </div></header>

6. Slim down app.js

Replace the whole file. Everything about issues has moved to the router; app.js keeps settings, middleware, mounting and error handling:

Replace whole filesrc/app.jsJavaScript
Highlighted lines are new or changed (5).
import express from 'express';import path from 'node:path';import { issuesRouter } from './routes/issues.js';import { organisationsRouter } from './routes/organisations.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((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 });});

app.use('/issues', issuesRouter) sends every request whose path starts with /issues to the router, with that prefix removed. The order of mounting still matters: routers come before the 404 handler.

7. Tests for organisations

Create filetest/organisations.test.jsJavaScript
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()); test('GET /organisations lists organisations with building counts', async () => {  const res = await request(app).get('/organisations');  assert.equal(res.status, 200);  assert.match(res.text, /Liffey Estates<\/a><\/td>\s*<td>2<\/td>/);  assert.match(res.text, /Harbour Lets/);}); test('GET /organisations/1 shows its buildings, not other organisations\' buildings', async () => {  const res = await request(app).get('/organisations/1');  assert.equal(res.status, 200);  assert.match(res.text, /Dublin Offices/);  assert.match(res.text, /Cork Apartments/);  assert.doesNotMatch(res.text, /Galway Studios/);}); test('POST /organisations validates and creates', async () => {  const bad = await request(app).post('/organisations').type('form').send({ name: ' ' });  assert.equal(bad.status, 400);  assert.match(bad.text, /Name must be between 2 and 100 characters/);   const good = await request(app).post('/organisations').type('form').send({ name: 'Riverside Lettings' });  assert.equal(good.status, 303);  const page = await request(app).get(good.headers.location);  assert.match(page.text, /<h1>Riverside Lettings<\/h1>/);}); test('POST /organisations/:id/edit renames the organisation', async () => {  const res = await request(app).post('/organisations/2/edit').type('form').send({ name: 'Harbour Lets Ltd' });  assert.equal(res.status, 303);  const page = await request(app).get('/organisations/2');  assert.match(page.text, /<h1>Harbour Lets Ltd<\/h1>/);}); test('unknown organisations are 404', async () => {  assert.equal((await request(app).get('/organisations/999')).status, 404);  assert.equal((await request(app).post('/organisations/999/edit').type('form').send({ name: 'Nope' })).status, 404);});

Run and inspect

Run and comparecaretaker/
npm test

> caretaker@1.0.0 test
> node --env-file=.env.test --test --test-concurrency=1 --test-reporter=spec "test/**/*.test.js"

✔ GET /issues lists issues from the database (65.192458ms)
✔ GET /issues/101 shows one issue with its building (3.015292ms)
✔ GET /issues/:id answers 404 for unknown or malformed ids (5.9875ms)
✔ POST /issues re-renders the form with errors (6.716125ms)
✔ POST /issues stores the issue and redirects to it (6.084041ms)
✔ POST /issues with a building that does not exist is a form error, not a 500 (16.792583ms)
✔ the stored row has the cleaned values (3.241417ms)
✔ GET /organisations lists organisations with building counts (53.028459ms)
✔ GET /organisations/1 shows its buildings, not other organisations' buildings (3.428709ms)
✔ POST /organisations validates and creates (10.27125ms)
✔ POST /organisations/:id/edit renames the organisation (5.611458ms)
✔ unknown organisations are 404 (4.552084ms)
ℹ tests 12
ℹ suites 0
ℹ pass 12
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 391.383125

Both test files ran, one after the other, each starting from a freshly seeded database. Start the app and look:

Server terminal (leave it running)caretaker/
npm run dev
> caretaker@1.0.0 dev
> node --env-file=.env --watch src/server.js

Caretaker listening on http://localhost:3000
localhost:3000/organisations/1
Organisation 1 with its two buildings and their issue counts.
Organisation 1 with its two buildings and their issue counts.

Experiment

Predict The route is organisationsRouter.get('/:id', ...). What does GET /organisations/new return, and why does it not try to load an organisation with the ID "new"?
Run and comparecaretaker/
curl -s http://localhost:3000/organisations/new | grep "<h1>"
<h1>New organisation</h1>
Reveal Answer

The router registered /new before /:id, and routers try routes in order, just like the app. Swap the two registrations and /organisations/new returns 404, because parseId('new') is null. Try it, then put the order back.

Ctrl+C Stop the server in the server terminal.

Checkpoint

Run and comparecaretaker/
npm test

> caretaker@1.0.0 test
> node --env-file=.env.test --test --test-concurrency=1 --test-reporter=spec "test/**/*.test.js"

✔ GET /issues lists issues from the database (68.240833ms)
✔ GET /issues/101 shows one issue with its building (3.808084ms)
✔ GET /issues/:id answers 404 for unknown or malformed ids (6.867417ms)
✔ POST /issues re-renders the form with errors (7.038625ms)
✔ POST /issues stores the issue and redirects to it (6.18575ms)
✔ POST /issues with a building that does not exist is a form error, not a 500 (9.519959ms)
✔ the stored row has the cleaned values (3.867292ms)
✔ GET /organisations lists organisations with building counts (53.907875ms)
✔ GET /organisations/1 shows its buildings, not other organisations' buildings (3.665667ms)
✔ POST /organisations validates and creates (9.790875ms)
✔ POST /organisations/:id/edit renames the organisation (5.303083ms)
✔ unknown organisations are 404 (4.21725ms)
ℹ tests 12
ℹ suites 0
ℹ pass 12
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 383.072416
Run and comparecaretaker/
git add -A
git commit -m "Organisations with routers"
[main 0d73888] Organisations with routers
 11 files changed, 306 insertions(+), 75 deletions(-)
 create mode 100644 src/lib/ids.js
 create mode 100644 src/models/organisations.js
 create mode 100644 src/routes/issues.js
 create mode 100644 src/routes/organisations.js
 create mode 100644 test/organisations.test.js
 create mode 100644 views/organisations/form.ejs
 create mode 100644 views/organisations/index.ejs
 create mode 100644 views/organisations/show.ejs
Symptom Cannot GET /issues after the refactor

app.use('/issues', issuesRouter) is missing, or the router's route is issuesRouter.get('/issues', ...) instead of issuesRouter.get('/', ...).

Symptom Building counts show as "2" (with quotes in JSON) or sort wrongly

The ::int cast is missing from count(...).

Recap and next step

Routers group the routes of one resource and are mounted at a prefix. Shared helpers (parseId) moved to src/lib. Organisations have list, show, create and edit, with one form template and a loadOrganisation helper that answers 404.

Next: deleting things safely, and buildings that belong to organisations.