Caretaker Express · PostgreSQL · Cedar

Checkpoint · Lesson 3.2

Buildings, unique names and safe deletes: checkpoint files

Git tag in the reference repository
lesson/m03-l02 (commit 6669662)
Replay result
All steps replayed from an empty folder
Tests at this point
pass (tests 18, pass 18, fail 0)

Compare your folder with the reference using Git, if you cloned it: git diff lesson/m03-l02 -- src.

Files changed in this lesson

public/js/app.js added

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();  }});

src/app.js changed

src/app.js
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 });});

src/lib/validation.js added

src/lib/validation.js
// 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 },  };}

src/models/buildings.js changed

src/models/buildings.js
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;}

src/models/issues.js changed

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 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];}

src/models/organisations.js changed

src/models/organisations.js
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;}

src/routes/buildings.js added

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}`);});

src/routes/organisations.js changed

src/routes/organisations.js
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;  }});

test/buildings.test.js added

test/buildings.test.js
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);});

views/buildings/form.ejs added

views/buildings/form.ejs
<%- 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') %>

views/buildings/show.ejs added

views/buildings/show.ejs
<%- 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') %>

views/organisations/show.ejs changed

views/organisations/show.ejs
<%- 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') %>

views/partials/head.ejs changed

views/partials/head.ejs
<!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">

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
public/js/app.js
scripts/migrate.js
scripts/seed.js
src/app.js
src/config.js
src/db.js
src/lib/ids.js
src/lib/validation.js
src/migrate.js
src/models/buildings.js
src/models/issues.js
src/models/organisations.js
src/routes/buildings.js
src/routes/issues.js
src/routes/organisations.js
src/seed.js
src/server.js
test/buildings.test.js
test/helpers.js
test/issues.test.js
test/organisations.test.js
views/buildings/form.ejs
views/buildings/show.ejs
views/error.ejs
views/issues/index.ejs
views/issues/new.ejs
views/issues/show.ejs
views/not-found.ejs
views/organisations/form.ejs
views/organisations/index.ejs
views/organisations/show.ejs
views/partials/foot.ejs
views/partials/head.ejs
views/partials/nav.ejs

Back to lesson 3.2