Module 3 · Build real CRUD features
3.2 Buildings, unique names and safe deletes
Create buildings inside an organisation, turn unique and restrict violations into clear messages, and add delete buttons that confirm before they act.
Starting point
Organisations can be listed, viewed, created and renamed. Their page lists buildings, but buildings have no pages, and nothing can be deleted.
Outcome
/organisations/1/buildings/newcreates a building in organisation 1. A duplicate name in the same organisation is a field error./buildings/10shows a building and its latest issues; it can be renamed.- Deleting an organisation that still has buildings, or a building that still has issues, is refused with
409 Conflictand an explanation. Empty ones are deleted. - Delete buttons ask for confirmation, using a few lines of vanilla JavaScript.
The problem
Deleting is the most dangerous thing a user can do. Our schema already refuses to delete parents with children (ON DELETE RESTRICT, lesson 2.2), so the data is safe. But right now the user would see the generic "Something went wrong" page. We want the database to keep enforcing the rule, and the app to explain it.
Build it
1. Data access
Add delete to src/models/organisations.js:
export async function deleteOrganisation(id) { const { rowCount } = await query('DELETE FROM organisations WHERE id = $1', [id]); return rowCount === 1;} export async function updateOrganisation(id, { name }) {
Show the whole src/models/organisations.js after this change
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 deleteOrganisation(id) { const { rowCount } = await query('DELETE FROM organisations WHERE id = $1', [id]); return rowCount === 1;} 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;}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 deleteOrganisation(id) {
const { rowCount } = await query('DELETE FROM organisations WHERE id = $1', [id]);
return rowCount === 1;
}
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;
}
And the building functions to src/models/buildings.js:
export async function findBuilding(id) { const { rows } = await query( `SELECT s.id, s.name, s.organisation_id, o.name AS organisation_name, s.created_at, s.updated_at FROM buildings s JOIN organisations o ON o.id = s.organisation_id WHERE s.id = $1`, [id], ); return rows[0] ?? null;} export async function createBuilding({ organisation_id, name }) { const { rows } = await query( 'INSERT INTO buildings (organisation_id, name) VALUES ($1, $2) RETURNING id', [organisation_id, name], ); return rows[0];} export async function updateBuilding(id, { name }) { const { rows } = await query('UPDATE buildings SET name = $2, updated_at = now() WHERE id = $1 RETURNING id', [id, name]); return rows[0] ?? null;} export async function deleteBuilding(id) { const { rowCount } = await query('DELETE FROM buildings WHERE id = $1', [id]); return rowCount === 1;} export async function listBuildingsForOrganisation(organisationId) {
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 findBuilding(id) { const { rows } = await query( `SELECT s.id, s.name, s.organisation_id, o.name AS organisation_name, s.created_at, s.updated_at FROM buildings s JOIN organisations o ON o.id = s.organisation_id WHERE s.id = $1`, [id], ); return rows[0] ?? null;} export async function createBuilding({ organisation_id, name }) { const { rows } = await query( 'INSERT INTO buildings (organisation_id, name) VALUES ($1, $2) RETURNING id', [organisation_id, name], ); return rows[0];} export async function updateBuilding(id, { name }) { const { rows } = await query('UPDATE buildings SET name = $2, updated_at = now() WHERE id = $1 RETURNING id', [id, name]); return rows[0] ?? null;} export async function deleteBuilding(id) { const { rowCount } = await query('DELETE FROM buildings WHERE id = $1', [id]); return rowCount === 1;} 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;}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 findBuilding(id) {
const { rows } = await query(
`SELECT s.id, s.name, s.organisation_id, o.name AS organisation_name, s.created_at, s.updated_at
FROM buildings s
JOIN organisations o ON o.id = s.organisation_id
WHERE s.id = $1`,
[id],
);
return rows[0] ?? null;
}
export async function createBuilding({ organisation_id, name }) {
const { rows } = await query(
'INSERT INTO buildings (organisation_id, name) VALUES ($1, $2) RETURNING id',
[organisation_id, name],
);
return rows[0];
}
export async function updateBuilding(id, { name }) {
const { rows } = await query('UPDATE buildings SET name = $2, updated_at = now() WHERE id = $1 RETURNING id', [id, name]);
return rows[0] ?? null;
}
export async function deleteBuilding(id) {
const { rowCount } = await query('DELETE FROM buildings WHERE id = $1', [id]);
return rowCount === 1;
}
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;
}
The building page shows the building's latest issues. Add a small query to src/models/issues.js:
export async function listRecentIssuesForBuilding(buildingId, limit = 10) { const { rows } = await query( `SELECT ${ISSUE_COLUMNS} FROM issues e JOIN buildings s ON s.id = e.building_id WHERE e.building_id = $1 ORDER BY e.occurred_at DESC, e.id DESC LIMIT $2`, [buildingId, limit], ); return rows;} export async function findIssue(id) {
Show the whole src/models/issues.js after this change
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 listRecentIssuesForBuilding(buildingId, limit = 10) { const { rows } = await query( `SELECT ${ISSUE_COLUMNS} FROM issues e JOIN buildings s ON s.id = e.building_id WHERE e.building_id = $1 ORDER BY e.occurred_at DESC, e.id DESC LIMIT $2`, [buildingId, limit], ); 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];}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 listRecentIssuesForBuilding(buildingId, limit = 10) {
const { rows } = await query(
`SELECT ${ISSUE_COLUMNS}
FROM issues e
JOIN buildings s ON s.id = e.building_id
WHERE e.building_id = $1
ORDER BY e.occurred_at DESC, e.id DESC
LIMIT $2`,
[buildingId, limit],
);
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];
}
LIMIT $2 shows that placeholders work for any value in a statement, not only in WHERE.
2. A shared name validator
Organisations and buildings both have a name of 2 to 100 characters. Create src/lib/validation.js so the rule lives in one place:
// Trims a string field and checks its length. Non-strings count as empty.export function cleanText(value, { min = 0, max }) { const text = typeof value === 'string' ? value.trim() : ''; const ok = text.length >= min && text.length <= max; return { text, ok };} export function validateName(input) { const { text, ok } = cleanText(input.name, { min: 2, max: 100 }); return { errors: ok ? {} : { name: 'Name must be between 2 and 100 characters.' }, values: { name: text }, };}Use it in the organisations router, and import what we need for buildings and deletes:
import { listOrganisations, findOrganisation, createOrganisation, updateOrganisation } from '../models/organisations.js';import { listBuildingsForOrganisation } from '../models/buildings.js';import { listOrganisations, findOrganisation, createOrganisation, updateOrganisation, deleteOrganisation } from '../models/organisations.js';import { listBuildingsForOrganisation, createBuilding } from '../models/buildings.js';import { PG_ERRORS } from '../db.js';import { parseId } from '../lib/ids.js';import { validateName } from '../lib/validation.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 } };}const validateOrganisation = validateName;
Show the whole src/routes/organisations.js after this change
import express from 'express';import { listOrganisations, findOrganisation, createOrganisation, updateOrganisation, deleteOrganisation } from '../models/organisations.js';import { listBuildingsForOrganisation, createBuilding } from '../models/buildings.js';import { PG_ERRORS } from '../db.js';import { parseId } from '../lib/ids.js';import { validateName } from '../lib/validation.js'; export const organisationsRouter = express.Router(); const validateOrganisation = validateName; 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}`);});import express from 'express';
import { listOrganisations, findOrganisation, createOrganisation, updateOrganisation, deleteOrganisation } from '../models/organisations.js';
import { listBuildingsForOrganisation, createBuilding } from '../models/buildings.js';
import { PG_ERRORS } from '../db.js';
import { parseId } from '../lib/ids.js';
import { validateName } from '../lib/validation.js';
export const organisationsRouter = express.Router();
const validateOrganisation = validateName;
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}`);
});
3. Delete an organisation
Add the delete route and the two "new building" routes at the end of src/routes/organisations.js:
await updateOrganisation(organisation.id, values); res.redirect(303, `/organisations/${organisation.id}`);}); organisationsRouter.post('/:id/delete', async (req, res) => { const organisation = await loadOrganisation(req, res); if (!organisation) return; try { await deleteOrganisation(organisation.id); } catch (err) { if (err.code === PG_ERRORS.RESTRICT_VIOLATION) { const buildings = await listBuildingsForOrganisation(organisation.id); return res.status(409).render('organisations/show', { title: organisation.name, organisation, buildings, error: 'This organisation still has buildings. Delete its buildings first.', }); } throw err; } res.redirect(303, '/organisations');}); function renderBuildingForm(res, status, { organisation, values = {}, errors = {} }) { res.status(status).render('buildings/form', { title: `New building in ${organisation.name}`, action: `/organisations/${organisation.id}/buildings`, cancelUrl: `/organisations/${organisation.id}`, building: null, values, errors, });} organisationsRouter.get('/:id/buildings/new', async (req, res) => { const organisation = await loadOrganisation(req, res); if (!organisation) return; renderBuildingForm(res, 200, { organisation });}); organisationsRouter.post('/:id/buildings', async (req, res) => { const organisation = await loadOrganisation(req, res); if (!organisation) return; const { errors, values } = validateName(req.body ?? {}); if (Object.keys(errors).length > 0) { return renderBuildingForm(res, 400, { organisation, values, errors }); } try { const building = await createBuilding({ organisation_id: organisation.id, name: values.name }); res.redirect(303, `/buildings/${building.id}`); } catch (err) { if (err.code === PG_ERRORS.UNIQUE_VIOLATION) { return renderBuildingForm(res, 400, { organisation, values, errors: { name: 'This organisation already has a building with that name.' } }); } throw err; }});
Show the whole src/routes/organisations.js after this change
import express from 'express';import { listOrganisations, findOrganisation, createOrganisation, updateOrganisation, deleteOrganisation } from '../models/organisations.js';import { listBuildingsForOrganisation, createBuilding } from '../models/buildings.js';import { PG_ERRORS } from '../db.js';import { parseId } from '../lib/ids.js';import { validateName } from '../lib/validation.js'; export const organisationsRouter = express.Router(); const validateOrganisation = validateName; 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}`);}); organisationsRouter.post('/:id/delete', async (req, res) => { const organisation = await loadOrganisation(req, res); if (!organisation) return; try { await deleteOrganisation(organisation.id); } catch (err) { if (err.code === PG_ERRORS.RESTRICT_VIOLATION) { const buildings = await listBuildingsForOrganisation(organisation.id); return res.status(409).render('organisations/show', { title: organisation.name, organisation, buildings, error: 'This organisation still has buildings. Delete its buildings first.', }); } throw err; } res.redirect(303, '/organisations');}); function renderBuildingForm(res, status, { organisation, values = {}, errors = {} }) { res.status(status).render('buildings/form', { title: `New building in ${organisation.name}`, action: `/organisations/${organisation.id}/buildings`, cancelUrl: `/organisations/${organisation.id}`, building: null, values, errors, });} organisationsRouter.get('/:id/buildings/new', async (req, res) => { const organisation = await loadOrganisation(req, res); if (!organisation) return; renderBuildingForm(res, 200, { organisation });}); organisationsRouter.post('/:id/buildings', async (req, res) => { const organisation = await loadOrganisation(req, res); if (!organisation) return; const { errors, values } = validateName(req.body ?? {}); if (Object.keys(errors).length > 0) { return renderBuildingForm(res, 400, { organisation, values, errors }); } try { const building = await createBuilding({ organisation_id: organisation.id, name: values.name }); res.redirect(303, `/buildings/${building.id}`); } catch (err) { if (err.code === PG_ERRORS.UNIQUE_VIOLATION) { return renderBuildingForm(res, 400, { organisation, values, errors: { name: 'This organisation already has a building with that name.' } }); } throw err; }});import express from 'express';
import { listOrganisations, findOrganisation, createOrganisation, updateOrganisation, deleteOrganisation } from '../models/organisations.js';
import { listBuildingsForOrganisation, createBuilding } from '../models/buildings.js';
import { PG_ERRORS } from '../db.js';
import { parseId } from '../lib/ids.js';
import { validateName } from '../lib/validation.js';
export const organisationsRouter = express.Router();
const validateOrganisation = validateName;
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}`);
});
organisationsRouter.post('/:id/delete', async (req, res) => {
const organisation = await loadOrganisation(req, res);
if (!organisation) return;
try {
await deleteOrganisation(organisation.id);
} catch (err) {
if (err.code === PG_ERRORS.RESTRICT_VIOLATION) {
const buildings = await listBuildingsForOrganisation(organisation.id);
return res.status(409).render('organisations/show', {
title: organisation.name,
organisation,
buildings,
error: 'This organisation still has buildings. Delete its buildings first.',
});
}
throw err;
}
res.redirect(303, '/organisations');
});
function renderBuildingForm(res, status, { organisation, values = {}, errors = {} }) {
res.status(status).render('buildings/form', {
title: `New building in ${organisation.name}`,
action: `/organisations/${organisation.id}/buildings`,
cancelUrl: `/organisations/${organisation.id}`,
building: null,
values,
errors,
});
}
organisationsRouter.get('/:id/buildings/new', async (req, res) => {
const organisation = await loadOrganisation(req, res);
if (!organisation) return;
renderBuildingForm(res, 200, { organisation });
});
organisationsRouter.post('/:id/buildings', async (req, res) => {
const organisation = await loadOrganisation(req, res);
if (!organisation) return;
const { errors, values } = validateName(req.body ?? {});
if (Object.keys(errors).length > 0) {
return renderBuildingForm(res, 400, { organisation, values, errors });
}
try {
const building = await createBuilding({ organisation_id: organisation.id, name: values.name });
res.redirect(303, `/buildings/${building.id}`);
} catch (err) {
if (err.code === PG_ERRORS.UNIQUE_VIOLATION) {
return renderBuildingForm(res, 400, { organisation, values, errors: { name: 'This organisation already has a building with that name.' } });
}
throw err;
}
});
deleteOrganisationis justDELETE. We do not count buildings first and then delete: another request could add a building between the two statements. TheRESTRICTrule is checked inside theDELETEitself.23001becomes409 Conflict: the request was valid, but it conflicts with the current state of the data.- The new building takes
organisation_idfrom the URL (/organisations/1/buildings), which we already loaded and checked, never from a form field. Keep this pattern in mind for Module 8. - The unique constraint
UNIQUE (organisation_id, name)from lesson 2.2 produces23505, which becomes a field error.
Show the error on the organisation page, and add the buttons:
<div class="actions"> <a class="btn" href="/organisations/<%= organisation.id %>/edit">Edit</a> <a class="btn" href="/organisations/<%= organisation.id %>/buildings/new">Add building</a> <form method="post" action="/organisations/<%= organisation.id %>/delete" data-confirm="Delete <%= organisation.name %>? This cannot be undone."> <button type="submit" class="btn btn-danger">Delete</button> </form> </div></div><% if (typeof error !== 'undefined' && error) { %> <div class="flash flash-error" role="alert"><%= error %></div><% } %>
<tr><td><%= building.name %></td><td><%= building.issue_count %></td></tr> <tr><td><a href="/buildings/<%= building.id %>"><%= building.name %></a></td><td><%= building.issue_count %></td></tr>
Show the whole views/organisations/show.ejs after this change
<%- 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> <a class="btn" href="/organisations/<%= organisation.id %>/buildings/new">Add building</a> <form method="post" action="/organisations/<%= organisation.id %>/delete" data-confirm="Delete <%= organisation.name %>? This cannot be undone."> <button type="submit" class="btn btn-danger">Delete</button> </form> </div></div><% if (typeof error !== 'undefined' && error) { %> <div class="flash flash-error" role="alert"><%= error %></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><a href="/buildings/<%= building.id %>"><%= building.name %></a></td><td><%= building.issue_count %></td></tr> <% } %> </tbody> </table><% } %><%- include('../partials/foot') %><%- 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>
<a class="btn" href="/organisations/<%= organisation.id %>/buildings/new">Add building</a>
<form method="post" action="/organisations/<%= organisation.id %>/delete" data-confirm="Delete <%= organisation.name %>? This cannot be undone.">
<button type="submit" class="btn btn-danger">Delete</button>
</form>
</div>
</div>
<% if (typeof error !== 'undefined' && error) { %>
<div class="flash flash-error" role="alert"><%= error %></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><a href="/buildings/<%= building.id %>"><%= building.name %></a></td><td><%= building.issue_count %></td></tr>
<% } %>
</tbody>
</table>
<% } %>
<%- include('../partials/foot') %>
typeof error !== 'undefined' is needed because the normal GET route does not pass error at all, and reading an undefined variable inside an EJS template throws a ReferenceError.
4. The buildings router
Create src/routes/buildings.js:
import express from 'express';import { findBuilding, updateBuilding, deleteBuilding } from '../models/buildings.js';import { listRecentIssuesForBuilding } from '../models/issues.js';import { PG_ERRORS } from '../db.js';import { parseId } from '../lib/ids.js';import { validateName } from '../lib/validation.js'; export const buildingsRouter = express.Router(); async function loadBuilding(req, res) { const id = parseId(req.params.id); const building = id === null ? null : await findBuilding(id); if (!building) { res.status(404).render('not-found', { title: 'Not found', path: req.originalUrl }); return null; } return building;} async function renderBuildingPage(res, status, building, error = null) { const issues = await listRecentIssuesForBuilding(building.id); res.status(status).render('buildings/show', { title: building.name, building, issues, error });} function renderEditForm(res, status, { building, values, errors = {} }) { res.status(status).render('buildings/form', { title: `Edit ${building.name}`, action: `/buildings/${building.id}/edit`, cancelUrl: `/buildings/${building.id}`, building, values, errors, });} buildingsRouter.get('/:id', async (req, res) => { const building = await loadBuilding(req, res); if (!building) return; await renderBuildingPage(res, 200, building);}); buildingsRouter.get('/:id/edit', async (req, res) => { const building = await loadBuilding(req, res); if (!building) return; renderEditForm(res, 200, { building, values: building });}); buildingsRouter.post('/:id/edit', async (req, res) => { const building = await loadBuilding(req, res); if (!building) return; const { errors, values } = validateName(req.body ?? {}); if (Object.keys(errors).length > 0) { return renderEditForm(res, 400, { building, values, errors }); } try { await updateBuilding(building.id, values); } catch (err) { if (err.code === PG_ERRORS.UNIQUE_VIOLATION) { return renderEditForm(res, 400, { building, values, errors: { name: 'This organisation already has a building with that name.' } }); } throw err; } res.redirect(303, `/buildings/${building.id}`);}); buildingsRouter.post('/:id/delete', async (req, res) => { const building = await loadBuilding(req, res); if (!building) return; try { await deleteBuilding(building.id); } catch (err) { if (err.code === PG_ERRORS.RESTRICT_VIOLATION) { return renderBuildingPage(res, 409, building, 'This building still has maintenance issues, so it cannot be deleted.'); } throw err; } res.redirect(303, `/organisations/${building.organisation_id}`);});Mount it in src/app.js:
import { organisationsRouter } from './routes/organisations.js';import { buildingsRouter } from './routes/buildings.js';
app.use('/organisations', organisationsRouter);app.use('/buildings', buildingsRouter);
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'; export const app = express(); app.set('view engine', 'ejs');app.set('views', path.join(import.meta.dirname, '..', 'views'));app.locals.formatDate = (value) => new Date(value).toLocaleString('en-IE', { dateStyle: 'medium', timeStyle: 'short', timeZone: 'UTC' }); app.use((req, res, next) => { if (process.env.NODE_ENV === 'test') { return next(); } const started = Date.now(); res.on('finish', () => { console.log(`${req.method} ${req.originalUrl} -> ${res.statusCode} (${Date.now() - started} ms)`); }); next();}); app.use(express.static(path.join(import.meta.dirname, '..', 'public')));app.use(express.urlencoded({ extended: false })); app.get('/', (req, res) => { res.redirect('/issues');}); app.use('/issues', issuesRouter);app.use('/organisations', organisationsRouter);app.use('/buildings', buildingsRouter); app.use((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';
export const app = express();
app.set('view engine', 'ejs');
app.set('views', path.join(import.meta.dirname, '..', 'views'));
app.locals.formatDate = (value) => new Date(value).toLocaleString('en-IE', { dateStyle: 'medium', timeStyle: 'short', timeZone: 'UTC' });
app.use((req, res, next) => {
if (process.env.NODE_ENV === 'test') {
return next();
}
const started = Date.now();
res.on('finish', () => {
console.log(`${req.method} ${req.originalUrl} -> ${res.statusCode} (${Date.now() - started} ms)`);
});
next();
});
app.use(express.static(path.join(import.meta.dirname, '..', 'public')));
app.use(express.urlencoded({ extended: false }));
app.get('/', (req, res) => {
res.redirect('/issues');
});
app.use('/issues', issuesRouter);
app.use('/organisations', organisationsRouter);
app.use('/buildings', buildingsRouter);
app.use((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 });
});
5. Building views
<%- include('../partials/head') %><p class="breadcrumbs"><a href="/organisations/<%= building.organisation_id %>"><%= building.organisation_name %></a> / Building #<%= building.id %></p><div class="page-header"> <h1><%= building.name %></h1> <div class="actions"> <a class="btn" href="/buildings/<%= building.id %>/edit">Edit</a> <form method="post" action="/buildings/<%= building.id %>/delete" data-confirm="Delete <%= building.name %>? This cannot be undone."> <button type="submit" class="btn btn-danger">Delete</button> </form> </div></div><% if (error) { %> <div class="flash flash-error" role="alert"><%= error %></div><% } %> <h2>Latest issues</h2><% if (issues.length === 0) { %> <p class="empty">No issues at this building.</p><% } else { %> <table class="data"> <thead><tr><th>Title</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><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') %><h1><%= title %></h1><form method="post" action="<%= action %>" class="form" novalidate> <div class="field<%= errors.name ? ' has-error' : '' %>"> <label for="name">Building 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"><%= building ? 'Save changes' : 'Create building' %></button> <a class="btn" href="<%= cancelUrl %>">Cancel</a> </div></form><%- include('../partials/foot') %>6. Confirm before deleting
A delete form posts immediately. Add a tiny script that asks first. Create public/js/app.js:
// Ask for confirmation before submitting any form with a data-confirm attribute.document.addEventListener('submit', (event) => { const form = event.target; const message = form.getAttribute('data-confirm'); if (message && !window.confirm(message)) { event.preventDefault(); }});Load it from the shared head. defer runs it after the page is parsed:
<link rel="stylesheet" href="/css/style.css"> <script src="/js/app.js" defer></script>
Show the whole views/partials/head.ejs after this change
<!doctype html><html lang="en"><head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title><%= title %> · Caretaker</title> <link rel="stylesheet" href="/css/style.css"> <script src="/js/app.js" defer></script></head><body><%- include('nav') %><main class="container"><!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title><%= title %> · Caretaker</title>
<link rel="stylesheet" href="/css/style.css">
<script src="/js/app.js" defer></script>
</head>
<body>
<%- include('nav') %>
<main class="container">
The script is a convenience only. A request sent with curl skips it, so the server-side rules (RESTRICT) are what actually protect the data.
7. Tests
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('a building can be created inside an organisation', async () => { const res = await request(app).post('/organisations/1/buildings').type('form').send({ name: 'Galway Townhouse' }); assert.equal(res.status, 303); const page = await request(app).get(res.headers.location); assert.match(page.text, /<h1>Galway Townhouse<\/h1>/); assert.match(page.text, /Liffey Estates/);}); test('a duplicate building name in the same organisation is a field error', async () => { const res = await request(app).post('/organisations/1/buildings').type('form').send({ name: 'Cork Apartments' }); assert.equal(res.status, 400); assert.match(res.text, /already has a building with that name/);}); test('the same building name is allowed in another organisation', async () => { const res = await request(app).post('/organisations/2/buildings').type('form').send({ name: 'Cork Apartments' }); assert.equal(res.status, 303);}); test('a building with issues cannot be deleted', async () => { const res = await request(app).post('/buildings/10/delete'); assert.equal(res.status, 409); assert.match(res.text, /still has maintenance issues/); assert.equal((await request(app).get('/buildings/10')).status, 200);}); test('an empty building can be deleted', async () => { const created = await request(app).post('/organisations/2/buildings').type('form').send({ name: 'Temporary Annex' }); const res = await request(app).post(`${created.headers.location}/delete`); assert.equal(res.status, 303); assert.equal(res.headers.location, '/organisations/2'); assert.equal((await request(app).get(created.headers.location)).status, 404);}); test('an organisation with buildings cannot be deleted, an empty one can', async () => { const blocked = await request(app).post('/organisations/1/delete'); assert.equal(blocked.status, 409); assert.match(blocked.text, /still has buildings/); const created = await request(app).post('/organisations').type('form').send({ name: 'Short-lived Ltd' }); const res = await request(app).post(`${created.headers.location}/delete`); assert.equal(res.status, 303); assert.equal((await request(app).get(created.headers.location)).status, 404);});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 (69.210375ms)
✔ a duplicate building name in the same organisation is a field error (3.14625ms)
✔ the same building name is allowed in another organisation (8.13625ms)
✔ a building with issues cannot be deleted (23.662875ms)
✔ an empty building can be deleted (7.131208ms)
✔ an organisation with buildings cannot be deleted, an empty one can (13.881583ms)
✔ GET /issues lists issues from the database (71.047625ms)
✔ GET /issues/101 shows one issue with its building (3.190458ms)
✔ GET /issues/:id answers 404 for unknown or malformed ids (7.09775ms)
✔ POST /issues re-renders the form with errors (6.49725ms)
✔ POST /issues stores the issue and redirects to it (5.772375ms)
✔ POST /issues with a building that does not exist is a form error, not a 500 (8.324042ms)
✔ the stored row has the cleaned values (3.522875ms)
✔ GET /organisations lists organisations with building counts (44.239167ms)
✔ GET /organisations/1 shows its buildings, not other organisations' buildings (3.415041ms)
✔ POST /organisations validates and creates (8.975ms)
✔ POST /organisations/:id/edit renames the organisation (5.231167ms)
✔ unknown organisations are 404 (4.064667ms)
ℹ tests 18
ℹ suites 0
ℹ pass 18
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 584.059209
npm run dev
> caretaker@1.0.0 dev
> node --env-file=.env --watch src/server.js
Caretaker listening on http://localhost:3000
Try to delete building 10 the way the browser does (a form POST), and read the status:
curl -si -X POST http://localhost:3000/buildings/10/delete | head -1
HTTP/1.1 409 Conflict

The browser asked "Delete Dublin Offices?" first; our screenshot tool accepts confirmation dialogs automatically.
Experiment
What if we had used ON DELETE CASCADE instead of RESTRICT? You can see the answer without changing the schema, inside a transaction that we roll back:
DELETE FROM buildings WHERE id = 10 remove in total?docker compose exec db psql -U caretaker caretaker, then paste the SQL.BEGIN;SELECT count(*) AS issues_at_building_10 FROM issues WHERE building_id = 10;ALTER TABLE issues DROP CONSTRAINT issues_building_id_fkey, ADD CONSTRAINT issues_building_id_fkey FOREIGN KEY (building_id) REFERENCES buildings (id) ON DELETE CASCADE;DELETE FROM buildings WHERE id = 10;SELECT count(*) AS issues_left_at_building_10 FROM issues WHERE building_id = 10;ROLLBACK;
BEGIN
issues_at_building_10
-----------------------
14
(1 row)
ALTER TABLE
DELETE 1
issues_left_at_building_10
----------------------------
0
(1 row)
ROLLBACKReveal What this shows
With CASCADE, one click would have silently deleted the building and every maintenance record at it. ROLLBACK undid both the schema change and the delete, so nothing happened. For records that a tenant or an insurer might ask about, an explicit, refused delete is the better default.
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 (66.24075ms)
✔ a duplicate building name in the same organisation is a field error (3.034625ms)
✔ the same building name is allowed in another organisation (9.19225ms)
✔ a building with issues cannot be deleted (24.107667ms)
✔ an empty building can be deleted (7.134417ms)
✔ an organisation with buildings cannot be deleted, an empty one can (14.369ms)
✔ GET /issues lists issues from the database (68.761834ms)
✔ GET /issues/101 shows one issue with its building (4.041667ms)
✔ GET /issues/:id answers 404 for unknown or malformed ids (6.735542ms)
✔ POST /issues re-renders the form with errors (6.476875ms)
✔ POST /issues stores the issue and redirects to it (5.955541ms)
✔ POST /issues with a building that does not exist is a form error, not a 500 (9.239667ms)
✔ the stored row has the cleaned values (3.607583ms)
✔ GET /organisations lists organisations with building counts (54.021958ms)
✔ GET /organisations/1 shows its buildings, not other organisations' buildings (4.157875ms)
✔ POST /organisations validates and creates (10.523375ms)
✔ POST /organisations/:id/edit renames the organisation (4.970375ms)
✔ unknown organisations are 404 (4.056416ms)
ℹ tests 18
ℹ suites 0
ℹ pass 18
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 610.841875
git add -A
git commit -m "Buildings and safe deletes"
[main 6a10b99] Buildings and safe deletes
13 files changed, 320 insertions(+), 11 deletions(-)
create mode 100644 public/js/app.js
create mode 100644 src/lib/validation.js
create mode 100644 src/routes/buildings.js
create mode 100644 test/buildings.test.js
create mode 100644 views/buildings/form.ejs
create mode 100644 views/buildings/show.ejs
Symptom ReferenceError: error is not defined on the organisation page
The template reads error but the route did not pass it. Use typeof error !== 'undefined' && error, as shown.
Symptom Deleting returns 500 instead of 409
Check the error code. A RESTRICT foreign key raises 23001; a NO ACTION foreign key (the default when you write no ON DELETE) raises 23503.
Recap and next step
Buildings live inside organisations, take their parent from the URL, and keep names unique per organisation through a database constraint. Deletes rely on RESTRICT and become 409 Conflict with a message. A few lines of JavaScript confirm deletes in the browser, while the server enforces the real rule.
Next, issues get the rest of their lifecycle: editing, changing status, moving between buildings, and deleting.
Open the checkpoint files for lesson 3.2 (separate page; only files from this lesson and earlier)