Checkpoint · Lesson 2.6
Safe writes and a test database: checkpoint files
Compare your folder with the reference using Git, if you cloned it: git diff lesson/m02-l06 -- src.
Files changed in this lesson
.env.test added
.env.test# Settings for automated tests. Local learning values only; safe to commit.
NODE_ENV=test
DATABASE_URL=postgres://caretaker:caretaker_dev_password@localhost:5433/caretaker_test
PORT=3001
LOG_SQL=0
# Settings for automated tests. Local learning values only; safe to commit.NODE_ENV=testDATABASE_URL=postgres://caretaker:caretaker_dev_password@localhost:5433/caretaker_testPORT=3001LOG_SQL=0package.json changed
package.json{
"name": "caretaker",
"version": "1.0.0",
"description": "",
"scripts": {
"test": "node --env-file=.env.test --test --test-concurrency=1 --test-reporter=spec \"test/**/*.test.js\"",
"start": "node --env-file=.env src/server.js",
"dev": "node --env-file=.env --watch src/server.js",
"db:migrate": "node --env-file=.env scripts/migrate.js",
"db:seed": "node --env-file=.env scripts/seed.js"
},
"keywords": [],
"author": "",
"license": "ISC",
"type": "module",
"dependencies": {
"ejs": "7.0.2",
"express": "5.3.0",
"pg": "8.23.1"
},
"devDependencies": {
"supertest": "7.3.2"
}
}
{ "name": "caretaker", "version": "1.0.0", "description": "", "scripts": { "test": "node --env-file=.env.test --test --test-concurrency=1 --test-reporter=spec \"test/**/*.test.js\"", "start": "node --env-file=.env src/server.js", "dev": "node --env-file=.env --watch src/server.js", "db:migrate": "node --env-file=.env scripts/migrate.js", "db:seed": "node --env-file=.env scripts/seed.js" }, "keywords": [], "author": "", "license": "ISC", "type": "module", "dependencies": { "ejs": "7.0.2", "express": "5.3.0", "pg": "8.23.1" }, "devDependencies": { "supertest": "7.3.2" }}src/app.js changed
src/app.jsimport express from 'express';
import path from 'node:path';
import { listIssues, findIssue, createIssue } from './models/issues.js';
import { listBuildings } from './models/buildings.js';
import { PG_ERRORS } from './db.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 });
}
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}`);
});
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';import { PG_ERRORS } from './db.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 }); } 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}`);}); 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 });});src/db.js changed
src/db.jsimport 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',
};
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',}; 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;}test/helpers.js added
test/helpers.jsimport { pool } from '../src/db.js';
import { config } from '../src/config.js';
import { migrate } from '../src/migrate.js';
import { seed } from '../src/seed.js';
export async function resetDatabase() {
if (!config.databaseUrl.endsWith('/caretaker_test')) {
throw new Error(`Refusing to reset ${config.databaseUrl}: tests only run against caretaker_test.`);
}
await migrate(config.databaseUrl, { log: () => {} });
const client = await pool.connect();
try {
await seed(client);
} finally {
client.release();
}
}
import { pool } from '../src/db.js';import { config } from '../src/config.js';import { migrate } from '../src/migrate.js';import { seed } from '../src/seed.js'; export async function resetDatabase() { if (!config.databaseUrl.endsWith('/caretaker_test')) { throw new Error(`Refusing to reset ${config.databaseUrl}: tests only run against caretaker_test.`); } await migrate(config.databaseUrl, { log: () => {} }); const client = await pool.connect(); try { await seed(client); } finally { client.release(); }}test/issues.test.js changed
test/issues.test.jsimport { 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 /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/);
});
test('POST /issues with a building that does not exist is a form error, not a 500', async () => {
const res = await request(app).post('/issues').type('form').send({ title: 'Ghost issue', building_id: '999', priority: 'low' });
assert.equal(res.status, 400);
assert.match(res.text, /Choose a building/);
});
test('the stored row has the cleaned values', async () => {
await request(app).post('/issues').type('form').send({ title: ' Spaces around ', building_id: '20', priority: 'medium', status: 'closed' });
const { rows } = await pool.query("SELECT title, building_id, status FROM issues WHERE title = 'Spaces around'");
assert.deepEqual(rows, [{ title: 'Spaces around', building_id: 20, status: 'open' }]);
});
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 /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/);}); test('POST /issues with a building that does not exist is a form error, not a 500', async () => { const res = await request(app).post('/issues').type('form').send({ title: 'Ghost issue', building_id: '999', priority: 'low' }); assert.equal(res.status, 400); assert.match(res.text, /Choose a building/);}); test('the stored row has the cleaned values', async () => { await request(app).post('/issues').type('form').send({ title: ' Spaces around ', building_id: '20', priority: 'medium', status: 'closed' }); const { rows } = await pool.query("SELECT title, building_id, status FROM issues WHERE title = 'Spaces around'"); assert.deepEqual(rows, [{ title: 'Spaces around', building_id: 20, status: 'open' }]);});Project tree at this checkpoint
.env.example
.env.test
.gitignore
.npmrc
compose.yaml
db/init/01-create-test-database.sql
migrations/001_create_organisations_buildings_issues.sql
package-lock.json
package.json
public/css/style.css
scripts/migrate.js
scripts/seed.js
src/app.js
src/config.js
src/db.js
src/migrate.js
src/models/buildings.js
src/models/issues.js
src/seed.js
src/server.js
test/helpers.js
test/issues.test.js
views/error.ejs
views/issues/index.ejs
views/issues/new.ejs
views/issues/show.ejs
views/not-found.ejs
views/partials/foot.ejs
views/partials/head.ejs
views/partials/nav.ejs