Module 2 · Persistence and the relational data model
2.5 Connect Express to PostgreSQL
Load configuration from the environment, share a connection pool, move SQL into small data-access functions, replace the in-memory array, and trace one request from route to SQL to HTML.
Starting point
The database holds the seeded scenario. The app still serves the old three-issue array, plus a JSON API under /api.
Outcome
caretaker/src/├── app.js (rewritten: pages read and write PostgreSQL)├── config.js (new: validated settings from the environment)├── db.js (new: one connection pool + a query helper)├── models/│ ├── issues.js (new: SQL for issues)│ └── buildings.js (new: SQL for buildings)├── migrate.js├── seed.js└── server.js/issues lists the 30 seeded issues, /issues/101 shows the stuck lift, and the form saves new issues into PostgreSQL. Issues survive a restart.
The problem
The pages read from an array. We need them to read from the database, which raises three questions that every database-backed app must answer:
- Where do settings come from? The database URL must not be hard-coded, and a missing setting should stop the app at startup, not on the first request.
- How do we manage connections? Opening a new connection for every request is slow (a TCP connection, authentication, a new server process), and the database limits how many connections it accepts.
- Where does SQL live? If every route builds its own SQL, the same query gets copied and drifts.
We also remove the JSON API. It was a good way to learn HTTP, but every extra endpoint is another place we must authenticate, authorize and test. From here on Caretaker has one interface: the browser pages.
Build it
1. Configuration
Create src/config.js:
function required(name) { const value = process.env[name]; if (!value) { throw new Error(`Missing required environment variable ${name}. Copy .env.example to .env.`); } return value;} export const config = { port: Number(process.env.PORT ?? 3000), databaseUrl: required('DATABASE_URL'), logSql: process.env.LOG_SQL === '1',};The module runs once, the first time anything imports it. If DATABASE_URL is missing it throws immediately, so the app refuses to start rather than failing later. Number(...) converts PORT from a string (lesson 0.3). LOG_SQL=1 will switch on a SQL log that we use to trace requests.
Document the new optional setting in .env.example:
# Copy this file to .env and adjust if needed. Never commit .env.DATABASE_URL=postgres://caretaker:caretaker_dev_password@localhost:5433/caretakerPORT=3000# Set to 1 to print every SQL statement the app runs.LOG_SQL=0cp .env.example .env
2. One pool for the whole app
Create src/db.js:
import pg from 'pg';import { config } from './config.js'; export const pool = new pg.Pool({ connectionString: config.databaseUrl, max: 10 }); 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;}- A
pg.Poolkeeps up tomaxopen connections and lends one to each query. When the query finishes, the connection goes back to the pool for the next request. Idle connections close after 10 seconds by default. pool.query(text, params)borrows a connection, runs one statement, and returns it. That is all most requests need. (Lesson 3.6 borrows a connection explicitly, for a transaction.)- Our
queryhelper wraps it so we can log every statement in one place. Only the SQL text and the parameter values are logged; there are no secrets in our queries yet. In Module 4 we keep password hashes out of this log. - The result object has
rows(an array of plain objects, one per row, keyed by column name) androwCount.
3. Data-access functions
Routes should say what they need ("the issue with id 101"), not how to fetch it. Create src/models/issues.js:
import { query } from '../db.js'; const ISSUE_COLUMNS = ` 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`; export async function listIssues() { const { rows } = await query( `SELECT ${ISSUE_COLUMNS} FROM issues e JOIN buildings s ON s.id = e.building_id ORDER BY e.occurred_at DESC, e.id DESC LIMIT 50`, ); return rows;} export async function findIssue(id) { const { rows } = await query( `SELECT ${ISSUE_COLUMNS} FROM issues e JOIN buildings s ON s.id = e.building_id WHERE e.id = $1`, [id], ); return rows[0] ?? null;} export async function createIssue({ building_id, title, description, priority }) { const { rows } = await query( `INSERT INTO issues (building_id, title, description, priority, occurred_at) VALUES ($1, $2, $3, $4, now()) RETURNING id`, [building_id, title, description, priority], ); return rows[0];}- Each issue row includes
building_nameandorganisation_idfrom the joined building. The organisation will matter a great deal in Module 5. LIMIT 50is a temporary safety net. Module 3 replaces it with real pagination.findIssuereturnsnullwhen no row matches, so routes can testif (!issue).- We name properties after their database columns (
building_id,occurred_at). The same names then appear in SQL, in JavaScript and in templates, with no mapping layer to get wrong.
And src/models/buildings.js, which the form needs for its building list:
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;}4. Rewrite app.js
Many lines change at once here: the array, the JSON API and its validation go, and every route becomes async. Replace the whole file. Changed and new lines are highlighted:
import express from 'express';import path from 'node:path';import { listIssues, findIssue, createIssue } from './models/issues.js';import { listBuildings } from './models/buildings.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 })); 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 = Number(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 (!Number.isInteger(buildingId) || buildingId <= 0) { 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 });} app.get('/', (req, res) => { res.redirect('/issues');}); app.get('/issues', async (req, res) => { const issues = await listIssues(); res.render('issues/index', { title: 'Maintenance issues', issues });}); app.get('/issues/new', async (req, res) => { await renderIssueForm(res, 200);}); app.post('/issues', async (req, res) => { const { errors, values } = validateIssue(req.body ?? {}); if (Object.keys(errors).length > 0) { return renderIssueForm(res, 400, { values, errors }); } const issue = await createIssue(values); res.redirect(303, `/issues/${issue.id}`);}); app.get('/issues/:id', async (req, res) => { const issue = await findIssue(Number(req.params.id)); if (!issue) { return res.status(404).render('not-found', { title: 'Not found', path: req.path }); } res.render('issues/show', { title: issue.title, issue });}); app.use((req, res) => { res.status(404).render('not-found', { title: 'Not found', path: req.path });}); 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 });});What changed and why:
- Imports of the data-access functions replace the
issuesarray andnextId. express.json()is gone with the JSON API. Forms are URL-encoded.validateIssuenow checks an optionaldescriptionand abuilding_idinstead of free-textbuilding. A form field is a string, so we convert withNumberand require a positive integer. Whether that building exists is a question for the database (next lesson).renderIssueFormloads the buildings and renders the form, so the GET and the failing POST cannot drift apart.- Every route that touches the database is
asyncandawaits the data function. If the query throws (database down, bad SQL), Express 5 passes the rejected promise to our error handler. - The 404 and error handlers only render pages now.
5. Update the templates
The rows have new column names. In the list, the building column and the date change:
<td><%= issue.building %></td> <td><%= issue.building_name %></td>
<td><%= formatDate(issue.occurredAt) %></td> <td><%= formatDate(issue.occurred_at) %></td>
Show the whole views/issues/index.ejs after this change
<%- include('../partials/head') %><div class="page-header"> <h1>Maintenance issues</h1> <a class="btn btn-primary" href="/issues/new">Report an issue</a></div> <% if (issues.length === 0) { %> <p class="empty">No issues yet.</p><% } else { %> <table class="data"> <thead> <tr><th>Title</th><th>Building</th><th>Priority</th><th>Status</th><th>Occurred</th></tr> </thead> <tbody> <% for (const issue of issues) { %> <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><span class="badge status-<%= issue.status %>"><%= issue.status %></span></td> <td><%= formatDate(issue.occurred_at) %></td> </tr> <% } %> </tbody> </table><% } %><%- include('../partials/foot') %><%- include('../partials/head') %>
<div class="page-header">
<h1>Maintenance issues</h1>
<a class="btn btn-primary" href="/issues/new">Report an issue</a>
</div>
<% if (issues.length === 0) { %>
<p class="empty">No issues yet.</p>
<% } else { %>
<table class="data">
<thead>
<tr><th>Title</th><th>Building</th><th>Priority</th><th>Status</th><th>Occurred</th></tr>
</thead>
<tbody>
<% for (const issue of issues) { %>
<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><span class="badge status-<%= issue.status %>"><%= issue.status %></span></td>
<td><%= formatDate(issue.occurred_at) %></td>
</tr>
<% } %>
</tbody>
</table>
<% } %>
<%- include('../partials/foot') %>
The issue page also shows the description:
<dt>Building</dt><dd><%= issue.building %></dd> <dt>Building</dt><dd><%= issue.building_name %></dd>
<dt>Occurred</dt><dd><%= formatDate(issue.occurredAt) %></dd> <dt>Occurred</dt><dd><%= formatDate(issue.occurred_at) %></dd></dl><% if (issue.description) { %> <h2>Description</h2> <p class="prose"><%= issue.description %></p><% } %>
Show the whole views/issues/show.ejs after this change
<%- include('../partials/head') %><p class="breadcrumbs"><a href="/issues">Issues</a> / #<%= issue.id %></p><div class="page-header"> <h1><%= issue.title %></h1></div><dl class="details"> <dt>Building</dt><dd><%= issue.building_name %></dd> <dt>Priority</dt><dd><span class="badge sev-<%= issue.priority %>"><%= issue.priority %></span></dd> <dt>Status</dt><dd><span class="badge status-<%= issue.status %>"><%= issue.status %></span></dd> <dt>Occurred</dt><dd><%= formatDate(issue.occurred_at) %></dd></dl><% if (issue.description) { %> <h2>Description</h2> <p class="prose"><%= issue.description %></p><% } %><%- include('../partials/foot') %><%- include('../partials/head') %>
<p class="breadcrumbs"><a href="/issues">Issues</a> / #<%= issue.id %></p>
<div class="page-header">
<h1><%= issue.title %></h1>
</div>
<dl class="details">
<dt>Building</dt><dd><%= issue.building_name %></dd>
<dt>Priority</dt><dd><span class="badge sev-<%= issue.priority %>"><%= issue.priority %></span></dd>
<dt>Status</dt><dd><span class="badge status-<%= issue.status %>"><%= issue.status %></span></dd>
<dt>Occurred</dt><dd><%= formatDate(issue.occurred_at) %></dd>
</dl>
<% if (issue.description) { %>
<h2>Description</h2>
<p class="prose"><%= issue.description %></p>
<% } %>
<%- include('../partials/foot') %>
In the form, the free-text building becomes a list of real buildings, and we add the description:
<div class="field<%= errors.building ? ' has-error' : '' %>"> <label for="building">Building</label> <input id="building" name="building" value="<%= values.building ?? '' %>" required> <% if (errors.building) { %><p class="field-error"><%= errors.building %></p><% } %> <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.description ? ' has-error' : '' %>"> <label for="description">Description <span class="muted">(optional)</span></label> <textarea id="description" name="description" maxlength="2000"><%= values.description ?? '' %></textarea> <% if (errors.description) { %><p class="field-error"><%= errors.description %></p><% } %> </div>
Show the whole views/issues/new.ejs after this change
<%- include('../partials/head') %><h1>Report a maintenance issue</h1> <% if (Object.keys(errors).length > 0) { %> <div class="error-summary" role="alert"> <p>Please fix the highlighted fields.</p> </div><% } %> <form method="post" action="/issues" class="form" novalidate> <div class="field<%= errors.title ? ' has-error' : '' %>"> <label for="title">Title</label> <input id="title" name="title" value="<%= values.title ?? '' %>" maxlength="200" required> <% if (errors.title) { %><p class="field-error"><%= errors.title %></p><% } %> </div> <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.description ? ' has-error' : '' %>"> <label for="description">Description <span class="muted">(optional)</span></label> <textarea id="description" name="description" maxlength="2000"><%= values.description ?? '' %></textarea> <% if (errors.description) { %><p class="field-error"><%= errors.description %></p><% } %> </div> <div class="field<%= errors.priority ? ' has-error' : '' %>"> <label for="priority">Priority</label> <select id="priority" name="priority"> <option value="">Choose…</option> <% for (const s of priorities) { %> <option value="<%= s %>"<%= values.priority === s ? ' selected' : '' %>><%= s %></option> <% } %> </select> <% if (errors.priority) { %><p class="field-error"><%= errors.priority %></p><% } %> </div> <div class="form-actions"> <button type="submit" class="btn btn-primary">Save issue</button> <a class="btn" href="/issues">Cancel</a> </div></form><%- include('../partials/foot') %><%- include('../partials/head') %>
<h1>Report a maintenance issue</h1>
<% if (Object.keys(errors).length > 0) { %>
<div class="error-summary" role="alert">
<p>Please fix the highlighted fields.</p>
</div>
<% } %>
<form method="post" action="/issues" class="form" novalidate>
<div class="field<%= errors.title ? ' has-error' : '' %>">
<label for="title">Title</label>
<input id="title" name="title" value="<%= values.title ?? '' %>" maxlength="200" required>
<% if (errors.title) { %><p class="field-error"><%= errors.title %></p><% } %>
</div>
<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.description ? ' has-error' : '' %>">
<label for="description">Description <span class="muted">(optional)</span></label>
<textarea id="description" name="description" maxlength="2000"><%= values.description ?? '' %></textarea>
<% if (errors.description) { %><p class="field-error"><%= errors.description %></p><% } %>
</div>
<div class="field<%= errors.priority ? ' has-error' : '' %>">
<label for="priority">Priority</label>
<select id="priority" name="priority">
<option value="">Choose…</option>
<% for (const s of priorities) { %>
<option value="<%= s %>"<%= values.priority === s ? ' selected' : '' %>><%= s %></option>
<% } %>
</select>
<% if (errors.priority) { %><p class="field-error"><%= errors.priority %></p><% } %>
</div>
<div class="form-actions">
<button type="submit" class="btn btn-primary">Save issue</button>
<a class="btn" href="/issues">Cancel</a>
</div>
</form>
<%- include('../partials/foot') %>
Every building from every organisation appears in this list. Remember that: it is one of the first things Module 5 must fix.
6. Use the configuration in the server and scripts
import { app } from './app.js';import { config } from './config.js'; app.listen(config.port, () => { console.log(`Caretaker listening on http://localhost:${config.port}`);});The app now needs .env to start. Update the two scripts:
npm pkg set scripts.start="node --env-file=.env src/server.js"
npm pkg set scripts.dev="node --env-file=.env --watch src/server.js"
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

Trace one request
Restart the server with the SQL log switched on. A variable on the command line overrides the value from .env:
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/issues/101 | grep -E "<h1>|<dd>"
<h1>Lift stuck between floors 2 and 3</h1>
<dt>Building</dt><dd>Dublin Offices</dd>
<dt>Priority</dt><dd><span class="badge sev-high">high</span></dd>
<dt>Status</dt><dd><span class="badge status-open">open</span></dd>
<dt>Occurred</dt><dd>2 Nov 2026, 09:15</dd>
SQL 28ms 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 WHERE e.id = $1 [101]
GET /issues/101 -> 200 (46 ms)
Follow the request from end to end:
GET /issues/101matched the route/issues/:id, soreq.params.idwas the string"101".- The route called
findIssue(Number("101")). findIssueranSELECT ... WHERE e.id = $1with the parameter[101]. The log shows the SQL text and the value separately, exactly aspgsent them to PostgreSQL.- PostgreSQL returned one row;
pgturned it into{ id: 101, building_name: 'Dublin Offices', occurred_at: Date, ... }. Note thattimestamptzcolumns arrive as JavaScriptDateobjects, which ourformatDateaccepts. - The route rendered
issues/show.ejswith that object, and the logger printed200.
See the pool
While the server is running, ask PostgreSQL who is connected. pg_stat_activity lists every connection; we exclude our own psql session:
docker compose exec db psql -U caretaker caretaker, then paste the SQL.SELECT pid, state, left(query, 50) AS last_queryFROM pg_stat_activityWHERE datname = 'caretaker' AND pid <> pg_backend_pid();
pid | state | last_query
-----+-------+--------------------------------------------
190 | idle | SELECT +
| | e.id, e.building_id, s.name AS building_
(1 row)The app's pooled connection stays open and idle after the request, ready for the next one. After 10 idle seconds the pool closes it.
Data that survives
Create an issue through the form with curl, then restart the server:
curl -i http://localhost:3000/issues --data-urlencode "title=Ladder with a cracked rung" --data-urlencode "building_id=20" --data-urlencode "priority=medium"
HTTP/1.1 303 See Other
X-Powered-By: Express
Location: /issues/131
Vary: Accept
Content-Type: text/plain; charset=utf-8
Content-Length: 37
Date: Sat, 28 Nov 2026 14:39:38 GMT
Connection: keep-alive
Keep-Alive: timeout=5
See Other. Redirecting to /issues/131
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/issues | grep "Ladder with a cracked rung"
<td><a href="/issues/131">Ladder with a cracked rung</a></td>
Still there. That was the first problem from lesson 1.5, solved.
Experiment
GET /issues/abc return now that the ID goes to PostgreSQL?curl -si http://localhost:3000/issues/abc | head -1
HTTP/1.1 500 Internal Server Error
> caretaker@1.0.0 dev
> node --env-file=.env --watch src/server.js
Caretaker listening on http://localhost:3000
GET /issues -> 200 (49 ms)
error: invalid input syntax for type integer: "NaN"
at /Users/you/code/caretaker/node_modules/pg-pool/index.js:45:11
at process.processTicksAndRejections (node:internal/process/task_queues:103:5)
at async query (file:///Users/you/code/caretaker/src/db.js:8:18)
at async findIssue (file:///Users/you/code/caretaker/src/models/issues.js:20:20)
at async file:///Users/you/code/caretaker/src/app.js:76:17 {
length: 146,
severity: 'ERROR',
code: '22P02',
detail: undefined,
hint: undefined,
position: undefined,
internalPosition: undefined,
internalQuery: undefined,
where: "unnamed portal parameter $1 = '...'",
schema: undefined,
table: undefined,
column: undefined,
dataType: undefined,
constraint: undefined,
file: 'numutils.c',
line: '615',
routine: 'pg_strtoint32_safe'
}
GET /issues/abc -> 500 (3 ms)
Reveal What happened
Number('abc') is NaN. pg sent the text NaN as the parameter, PostgreSQL could not turn it into an integer (22P02 invalid input syntax for type integer), the query rejected, and our error handler answered 500. The user typed a bad URL; that is not a server error. Large numbers fail the same way: integer stops at 2147483647.
Fix it by validating IDs before they reach SQL. Add a helper above validateIssue:
const PRIORITIES = ['low', 'medium', 'high', 'critical'];const MAX_INTEGER = 2147483647; // Returns a positive integer that fits a PostgreSQL integer column, or null.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;}
Show the whole src/app.js after this change
import express from 'express';import path from 'node:path';import { listIssues, findIssue, createIssue } from './models/issues.js';import { listBuildings } from './models/buildings.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 })); const PRIORITIES = ['low', 'medium', 'high', 'critical'];const MAX_INTEGER = 2147483647; // Returns a positive integer that fits a PostgreSQL integer column, or null.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;} 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 = Number(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 (!Number.isInteger(buildingId) || buildingId <= 0) { 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 });} app.get('/', (req, res) => { res.redirect('/issues');}); app.get('/issues', async (req, res) => { const issues = await listIssues(); res.render('issues/index', { title: 'Maintenance issues', issues });}); app.get('/issues/new', async (req, res) => { await renderIssueForm(res, 200);}); app.post('/issues', async (req, res) => { const { errors, values } = validateIssue(req.body ?? {}); if (Object.keys(errors).length > 0) { return renderIssueForm(res, 400, { values, errors }); } const issue = await createIssue(values); res.redirect(303, `/issues/${issue.id}`);}); app.get('/issues/:id', async (req, res) => { const issue = await findIssue(Number(req.params.id)); if (!issue) { return res.status(404).render('not-found', { title: 'Not found', path: req.path }); } res.render('issues/show', { title: issue.title, issue });}); app.use((req, res) => { res.status(404).render('not-found', { title: 'Not found', path: req.path });}); 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 { listIssues, findIssue, createIssue } from './models/issues.js';
import { listBuildings } from './models/buildings.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 }));
const PRIORITIES = ['low', 'medium', 'high', 'critical'];
const MAX_INTEGER = 2147483647;
// Returns a positive integer that fits a PostgreSQL integer column, or null.
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;
}
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 = Number(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 (!Number.isInteger(buildingId) || buildingId <= 0) {
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 });
}
app.get('/', (req, res) => {
res.redirect('/issues');
});
app.get('/issues', async (req, res) => {
const issues = await listIssues();
res.render('issues/index', { title: 'Maintenance issues', issues });
});
app.get('/issues/new', async (req, res) => {
await renderIssueForm(res, 200);
});
app.post('/issues', async (req, res) => {
const { errors, values } = validateIssue(req.body ?? {});
if (Object.keys(errors).length > 0) {
return renderIssueForm(res, 400, { values, errors });
}
const issue = await createIssue(values);
res.redirect(303, `/issues/${issue.id}`);
});
app.get('/issues/:id', async (req, res) => {
const issue = await findIssue(Number(req.params.id));
if (!issue) {
return res.status(404).render('not-found', { title: 'Not found', path: req.path });
}
res.render('issues/show', { title: issue.title, issue });
});
app.use((req, res) => {
res.status(404).render('not-found', { title: 'Not found', path: req.path });
});
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 });
});
Use it for the route parameter, and for building_id in the form validation:
const issue = await findIssue(Number(req.params.id)); const id = parseId(req.params.id); const issue = id === null ? null : await findIssue(id);
const buildingId = Number(input.building_id); const buildingId = parseId(input.building_id);
if (!Number.isInteger(buildingId) || buildingId <= 0) { if (buildingId === null) {
Show the whole src/app.js after this change
import express from 'express';import path from 'node:path';import { listIssues, findIssue, createIssue } from './models/issues.js';import { listBuildings } from './models/buildings.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 })); const PRIORITIES = ['low', 'medium', 'high', 'critical'];const MAX_INTEGER = 2147483647; // Returns a positive integer that fits a PostgreSQL integer column, or null.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;} 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 });} app.get('/', (req, res) => { res.redirect('/issues');}); app.get('/issues', async (req, res) => { const issues = await listIssues(); res.render('issues/index', { title: 'Maintenance issues', issues });}); app.get('/issues/new', async (req, res) => { await renderIssueForm(res, 200);}); app.post('/issues', async (req, res) => { const { errors, values } = validateIssue(req.body ?? {}); if (Object.keys(errors).length > 0) { return renderIssueForm(res, 400, { values, errors }); } const issue = await createIssue(values); res.redirect(303, `/issues/${issue.id}`);}); app.get('/issues/: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.path }); } res.render('issues/show', { title: issue.title, issue });}); app.use((req, res) => { res.status(404).render('not-found', { title: 'Not found', path: req.path });}); 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 { listIssues, findIssue, createIssue } from './models/issues.js';
import { listBuildings } from './models/buildings.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 }));
const PRIORITIES = ['low', 'medium', 'high', 'critical'];
const MAX_INTEGER = 2147483647;
// Returns a positive integer that fits a PostgreSQL integer column, or null.
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;
}
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 });
}
app.get('/', (req, res) => {
res.redirect('/issues');
});
app.get('/issues', async (req, res) => {
const issues = await listIssues();
res.render('issues/index', { title: 'Maintenance issues', issues });
});
app.get('/issues/new', async (req, res) => {
await renderIssueForm(res, 200);
});
app.post('/issues', async (req, res) => {
const { errors, values } = validateIssue(req.body ?? {});
if (Object.keys(errors).length > 0) {
return renderIssueForm(res, 400, { values, errors });
}
const issue = await createIssue(values);
res.redirect(303, `/issues/${issue.id}`);
});
app.get('/issues/: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.path });
}
res.render('issues/show', { title: issue.title, issue });
});
app.use((req, res) => {
res.status(404).render('not-found', { title: 'Not found', path: req.path });
});
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 });
});
curl -si http://localhost:3000/issues/abc | head -1
HTTP/1.1 404 Not Found
curl -si http://localhost:3000/issues/99999999999 | head -1
HTTP/1.1 404 Not Found
Checkpoint
The tests from lesson 1.5 test the JSON API, which no longer exists. Replace the test file with tests for the database-backed pages:
import { test, 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'; after(() => pool.end()); test('GET /issues lists issues from the database', async () => { const res = await request(app).get('/issues'); assert.equal(res.status, 200); assert.match(res.text, /Lift stuck between floors 2 and 3/);}); test('GET /issues/101 shows one issue with its building', async () => { const res = await request(app).get('/issues/101'); assert.equal(res.status, 200); assert.match(res.text, /<h1>Lift stuck between floors 2 and 3<\/h1>/); assert.match(res.text, /Dublin Offices/);}); test('GET /issues/:id answers 404 for unknown or malformed ids', async () => { for (const id of ['999999', 'abc', '0', '99999999999']) { const res = await request(app).get(`/issues/${id}`); assert.equal(res.status, 404, `id ${id}`); }}); test('POST /issues re-renders the form with errors', async () => { const res = await request(app).post('/issues').type('form').send({ title: '', building_id: '', priority: '' }); assert.equal(res.status, 400); assert.match(res.text, /Choose a building/);}); test('POST /issues stores the issue and redirects to it', async () => { const res = await request(app) .post('/issues') .type('form') .send({ title: 'Water leak by the staff entrance', building_id: '10', priority: 'low' }); assert.equal(res.status, 303); const page = await request(app).get(res.headers.location); assert.equal(page.status, 200); assert.match(page.text, /Water leak by the staff entrance/);});after(() => pool.end()) closes the pool when the file's tests finish. Without it, the open idle connections keep Node running for another 10 seconds.
The tests now need DATABASE_URL. For this lesson, point them at .env:
npm pkg set scripts.test="NODE_ENV=test node --env-file=.env --test --test-reporter=spec"
npm test
> caretaker@1.0.0 test
> NODE_ENV=test node --env-file=.env --test --test-reporter=spec
✔ GET /issues lists issues from the database (39.734167ms)
✔ GET /issues/101 shows one issue with its building (4.392625ms)
✔ GET /issues/:id answers 404 for unknown or malformed ids (6.606125ms)
✔ POST /issues re-renders the form with errors (10.739416ms)
✔ POST /issues stores the issue and redirects to it (13.673333ms)
ℹ tests 5
ℹ suites 0
ℹ pass 5
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 178.103959
git add -A
git commit -m "Read and write issues in PostgreSQL"
[main 7623ec5] Read and write issues in PostgreSQL
12 files changed, 167 insertions(+), 106 deletions(-)
create mode 100644 src/config.js
create mode 100644 src/db.js
create mode 100644 src/models/buildings.js
create mode 100644 src/models/issues.js
Symptom Error: Missing required environment variable DATABASE_URL
Start the app with npm run dev or npm start, which pass --env-file=.env, and check that .env exists.
Symptom The list is empty
The database is not seeded. Run npm run db:migrate and npm run db:seed.
Symptom column e.building does not exist or a template shows blank buildings
A template still uses issue.building or issue.occurredAt. The new names are building_name and occurred_at.
Recap and next step
Configuration comes from the environment and is checked at startup. One pg.Pool serves all requests. SQL lives in small data-access functions that return plain objects named after their columns. IDs from URLs are validated before they reach SQL. And you traced a request: route parameter, parsed ID, parameterized SQL, row, template, response.
Look at what the tests just did, though: they created "Water leak by the staff entrance" in your development database. Run them twice and you get two. Next lesson gives the tests their own database, and looks closely at why those $1 placeholders matter.
Open the checkpoint files for lesson 2.5 (separate page; only files from this lesson and earlier)