Module 3 · Build real CRUD features
3.6 A dashboard, and the CRUD app as a whole
Summarise issues and inspections with aggregate SQL and FILTER clauses, run independent queries in parallel, and review what the application can do before we add users.
Starting point
Every resource has its pages, but / just redirects to /issues.
Outcome
/ shows a dashboard: open issues, serious open issues, inspections waiting for approval, a table of buildings with their open and total issue counts, and the five most recent issues. One small model file holds the SQL.
The problem
A dashboard needs numbers from several tables. The naive way loads every issue into JavaScript and counts with filter(...).length. That moves thousands of rows over the network to compute three integers, and gets slower every day. The database is built to count; we should ask it to.
Build it
1. Aggregate queries
Create src/models/dashboard.js:
import { query } from '../db.js';import { listIssues } from './issues.js'; export async function getDashboard() { const [issueCounts, inspectionCounts, buildings, recent] = await Promise.all([ query( `SELECT count(*) FILTER (WHERE status <> 'closed')::int AS open_issues, count(*) FILTER (WHERE status <> 'closed' AND priority IN ('high', 'critical'))::int AS serious_open_issues FROM issues`, ), query("SELECT count(*)::int AS awaiting_approval FROM inspections WHERE status = 'submitted'"), query( `SELECT s.id, s.name, o.name AS organisation_name, count(e.id) FILTER (WHERE e.status <> 'closed')::int AS open_issues, count(e.id)::int AS total_issues FROM buildings s JOIN organisations o ON o.id = s.organisation_id LEFT JOIN issues e ON e.building_id = s.id GROUP BY s.id, o.name ORDER BY o.name, s.name`, ), listIssues({ perPage: 5 }), ]); return { ...issueCounts.rows[0], ...inspectionCounts.rows[0], buildings: buildings.rows, recentIssues: recent.issues, };}count(*) FILTER (WHERE ...)counts only the rows that match the condition. Two different counts come from one pass over the table.Promise.allstarts all four queries at once. They do not depend on each other, and the pool lends each its own connection, so the page waits for the slowest query instead of the sum of all four.listIssues({ perPage: 5 })reuses the list function from lesson 3.4, with its default sort (newest first).
2. The route and the view
Replace the redirect in src/app.js:
import { inspectionsRouter } from './routes/inspections.js';import { getDashboard } from './models/dashboard.js';
app.get('/', (req, res) => { res.redirect('/issues');app.get('/', async (req, res) => { res.render('dashboard', { title: 'Dashboard', dashboard: await getDashboard() });});
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';import { getDashboard } from './models/dashboard.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('/', async (req, res) => { res.render('dashboard', { title: 'Dashboard', dashboard: await getDashboard() });}); 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';
import { getDashboard } from './models/dashboard.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('/', async (req, res) => {
res.render('dashboard', { title: 'Dashboard', dashboard: await getDashboard() });
});
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 });
});
<%- include('partials/head') %><h1>Dashboard</h1><div class="cards"> <div class="card"><h3>Open issues</h3><div class="stat"><%= dashboard.open_issues %></div><p class="muted">open or under investigation</p></div> <div class="card"><h3>Serious and open</h3><div class="stat"><%= dashboard.serious_open_issues %></div><p class="muted">high or critical priority</p></div> <div class="card"><h3>Inspections awaiting approval</h3><div class="stat"><%= dashboard.awaiting_approval %></div><p class="muted"><a href="/inspections?status=submitted">review them</a></p></div></div> <h2>Buildings</h2><table class="data"> <thead><tr><th>Building</th><th>Organisation</th><th>Open issues</th><th>All issues</th></tr></thead> <tbody> <% for (const building of dashboard.buildings) { %> <tr> <td><a href="/buildings/<%= building.id %>"><%= building.name %></a></td> <td><%= building.organisation_name %></td> <td><a href="/issues?building=<%= building.id %>&status=open"><%= building.open_issues %></a></td> <td><%= building.total_issues %></td> </tr> <% } %> </tbody></table> <h2>Recent issues</h2><table class="data"> <thead><tr><th>Title</th><th>Building</th><th>Priority</th><th>Occurred</th></tr></thead> <tbody> <% for (const issue of dashboard.recentIssues) { %> <tr> <td><a href="/issues/<%= issue.id %>"><%= issue.title %></a></td> <td><%= issue.building_name %></td> <td><span class="badge sev-<%= issue.priority %>"><%= issue.priority %></span></td> <td><%= formatDate(issue.occurred_at) %></td> </tr> <% } %> </tbody></table><%- include('partials/foot') %>One detail: the "open issues" link uses status=open, which lists issues whose status is exactly open, while the count includes investigating. Read the numbers with that in mind, or change the count if your users would expect otherwise; it is a product decision, not a technical one.
3. A test that checks the numbers against SQL
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('the dashboard counts match the database', async () => { const res = await request(app).get('/'); assert.equal(res.status, 200); const { rows } = await pool.query("SELECT count(*)::int AS n FROM issues WHERE status <> 'closed'"); assert.match(res.text, new RegExp(`<h3>Open issues</h3><div class="stat">${rows[0].n}</div>`)); assert.match(res.text, /<h3>Inspections awaiting approval<\/h3><div class="stat">2<\/div>/);}); test('every building appears with its organisation', async () => { const res = await request(app).get('/'); for (const name of ['Dublin Offices', 'Cork Apartments', 'Galway Studios', 'Limerick House']) { assert.match(res.text, new RegExp(name)); }});Run and inspect
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 (68.467ms)
✔ a duplicate building name in the same organisation is a field error (3.144334ms)
✔ the same building name is allowed in another organisation (7.746542ms)
✔ a building with issues cannot be deleted (22.158666ms)
✔ an empty building can be deleted (6.632375ms)
✔ an organisation with buildings cannot be deleted, an empty one can (13.320166ms)
✔ the dashboard counts match the database (72.240417ms)
✔ every building appears with its organisation (4.255708ms)
✔ create a draft, edit it, submit it, approve it (82.968542ms)
✔ invalid transitions are refused with 409 and change nothing (7.919625ms)
✔ only drafts can be edited (2.984ms)
✔ returning a submitted inspection makes it editable again (5.559208ms)
✔ concurrent approvals: exactly one wins (19.867208ms)
✔ unknown actions are 404 (1.313792ms)
✔ the list pages 10 at a time and reports the total (80.775833ms)
✔ pages do not overlap (9.85425ms)
✔ filters combine with AND (3.405ms)
✔ sorting by priority puts critical first when descending (2.706334ms)
✔ unknown sort keys and SQL in the query string are ignored (19.099ms)
✔ GET /issues lists issues from the database (67.404708ms)
✔ GET /issues/101 shows one issue with its building (3.80875ms)
✔ GET /issues/:id answers 404 for unknown or malformed ids (5.432417ms)
✔ POST /issues re-renders the form with errors (5.855834ms)
✔ POST /issues stores the issue and redirects to it (5.264375ms)
✔ POST /issues with a building that does not exist is a form error, not a 500 (9.321916ms)
✔ the stored row has the cleaned values and ignores a client-sent status (3.127083ms)
✔ an issue time in the future is rejected (2.273875ms)
✔ GET /issues/101/edit shows the current values (2.18975ms)
✔ POST /issues/:id/edit changes the status and updated_at (3.174167ms)
✔ POST /issues/:id/delete removes the issue (3.975125ms)
✔ GET /organisations lists organisations with building counts (64.624375ms)
✔ GET /organisations/1 shows its buildings, not other organisations' buildings (3.656584ms)
✔ POST /organisations validates and creates (10.711166ms)
✔ POST /organisations/:id/edit renames the organisation (5.880291ms)
✔ unknown organisations are 404 (4.1ms)
ℹ tests 35
Show 7 more lines
ℹ suites 0
ℹ pass 35
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 1217.268666
Your development database still holds the changes from the last lesson's experiments (approved inspections, edited issues). Reset it to the scenario so your dashboard matches ours:
npm run db:seed
> caretaker@1.0.0 db:seed
> node --env-file=.env scripts/seed.js
seeded the Caretaker scenario
LOG_SQL=1 npm run dev
> caretaker@1.0.0 dev
> node --env-file=.env --watch src/server.js
Caretaker listening on http://localhost:3000

curl -s http://localhost:3000/ > /dev/null
(no output)
SQL 1ms SELECT count(*) FILTER (WHERE status <> 'closed')::int AS open_issues, count(*) FILTER (WHERE status <> 'closed' AND priority IN ('high', 'critical'))::int AS serious_open_issues FROM issues []
SQL 1ms SELECT count(*)::int AS awaiting_approval FROM inspections WHERE status = 'submitted' []
SQL 2ms SELECT count(*)::int AS total FROM issues e JOIN buildings s ON s.id = e.building_id []
SQL 3ms SELECT s.id, s.name, o.name AS organisation_name, count(e.id) FILTER (WHERE e.status <> 'closed')::int AS open_issues, count(e.id)::int AS total_issues FROM buildings s JOIN organisations o ON o.id = s.organisation_id LEFT JOIN issues e ON e.building_id = s.id GROUP BY s.id, o.name ORDER BY o.name, s.name []
SQL 1ms SELECT e.id, e.building_id, s.name AS building_name, s.organisation_id, e.title, e.description, e.priority, e.status, e.occurred_at, e.created_at, e.updated_at FROM issues e JOIN buildings s ON s.id = e.building_id ORDER BY e.occurred_at DESC, e.id DESC LIMIT $1 OFFSET $2 [5,0]
GET / -> 200 (5 ms)
Look at the timings in the log. The four queries started together, so the request took roughly as long as the slowest one, not their sum.
Experiment
Our CRUD application is now complete. Before Module 4, take stock of something uncomfortable.
/ see?Reveal Answer
All of it. The dashboard counts Liffey Estates' and Harbour Lets' issues together, the building list shows both companies, and anyone who can reach the server can edit or delete anything. Nothing identifies the visitor yet. That is acceptable only because this app runs on your laptop with made-up data. The next module adds identity (who are you?), and the module after it adds authorization (what may you do?).
Make a list, now, of every place that will need an authorization decision. Then open the hint.
Hint Our list
Every route: each list (/issues, /inspections, /organisations, the dashboard), each "load by id" helper (loadIssue, loadInspection, loadBuilding, loadOrganisation), each create (which building? which organisation?), each update (including moving an issue to another building), each delete, and each inspection transition. Also every <select> of buildings in a form, which today lists every building in the database.
Checkpoint
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 (74.399209ms)
✔ a duplicate building name in the same organisation is a field error (3.394083ms)
✔ the same building name is allowed in another organisation (9.489667ms)
✔ a building with issues cannot be deleted (25.368417ms)
✔ an empty building can be deleted (7.687542ms)
✔ an organisation with buildings cannot be deleted, an empty one can (14.388541ms)
✔ the dashboard counts match the database (76.187167ms)
✔ every building appears with its organisation (4.741916ms)
✔ create a draft, edit it, submit it, approve it (87.443875ms)
✔ invalid transitions are refused with 409 and change nothing (8.198083ms)
✔ only drafts can be edited (3.098625ms)
✔ returning a submitted inspection makes it editable again (6.460209ms)
✔ concurrent approvals: exactly one wins (19.342417ms)
✔ unknown actions are 404 (1.398375ms)
✔ the list pages 10 at a time and reports the total (77.531959ms)
✔ pages do not overlap (10.395167ms)
✔ filters combine with AND (3.6435ms)
✔ sorting by priority puts critical first when descending (2.752792ms)
✔ unknown sort keys and SQL in the query string are ignored (17.936833ms)
✔ GET /issues lists issues from the database (59.4625ms)
✔ GET /issues/101 shows one issue with its building (3.222834ms)
✔ GET /issues/:id answers 404 for unknown or malformed ids (5.725375ms)
✔ POST /issues re-renders the form with errors (6.250833ms)
✔ POST /issues stores the issue and redirects to it (5.167458ms)
✔ POST /issues with a building that does not exist is a form error, not a 500 (9.144917ms)
✔ the stored row has the cleaned values and ignores a client-sent status (3.372708ms)
✔ an issue time in the future is rejected (1.975708ms)
✔ GET /issues/101/edit shows the current values (2.249084ms)
✔ POST /issues/:id/edit changes the status and updated_at (3.055625ms)
✔ POST /issues/:id/delete removes the issue (4.430708ms)
✔ GET /organisations lists organisations with building counts (102.835917ms)
✔ GET /organisations/1 shows its buildings, not other organisations' buildings (5.705375ms)
✔ POST /organisations validates and creates (12.635042ms)
✔ POST /organisations/:id/edit renames the organisation (6.190333ms)
✔ unknown organisations are 404 (4.426708ms)
ℹ tests 35
Show 7 more lines
ℹ suites 0
ℹ pass 35
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 1311.093292
git add -A
git commit -m "Dashboard"
[main bdf8921] Dashboard
4 files changed, 95 insertions(+), 2 deletions(-)
create mode 100644 src/models/dashboard.js
create mode 100644 test/dashboard.test.js
create mode 100644 views/dashboard.ejs
Symptom A count shows as text such as "12" or the regex in the test fails
A count(...) is missing its ::int cast.
Recap and next step
Aggregates belong in SQL: count(*) FILTER (WHERE ...) computes several counts in one pass, and Promise.all runs independent queries in parallel. Module 3 is complete: organisations, buildings, issues and inspections, with validation, safe deletes, paging, sorting, filtering, a transactional workflow and 35 tests.
The application has no idea who is using it. Module 4 adds users, passwords, sessions and the protections that come with them.
Open the checkpoint files for lesson 3.6 (separate page; only files from this lesson and earlier)