Caretaker Express · PostgreSQL · Cedar

Checkpoint · Lesson 3.1

Routers, and organisations you can create and edit: checkpoint files

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

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

Files changed in this lesson

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'; 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((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/ids.js added

src/lib/ids.js
const MAX_INTEGER = 2147483647; // Returns a positive integer that fits a PostgreSQL integer column, or null.export 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;}

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 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/organisations.js added

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 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/issues.js added

src/routes/issues.js
import express from 'express';import { listIssues, findIssue, createIssue } from '../models/issues.js';import { listBuildings } from '../models/buildings.js';import { PG_ERRORS } from '../db.js';import { parseId } from '../lib/ids.js'; export const issuesRouter = express.Router(); 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 = 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 });} issuesRouter.get('/', async (req, res) => {  const issues = await listIssues();  res.render('issues/index', { title: 'Maintenance issues', issues });}); issuesRouter.get('/new', async (req, res) => {  await renderIssueForm(res, 200);}); issuesRouter.post('/', 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}`);}); issuesRouter.get('/: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.originalUrl });  }  res.render('issues/show', { title: issue.title, issue });});

src/routes/organisations.js added

src/routes/organisations.js
import express from 'express';import { listOrganisations, findOrganisation, createOrganisation, updateOrganisation } from '../models/organisations.js';import { listBuildingsForOrganisation } from '../models/buildings.js';import { parseId } from '../lib/ids.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 } };} 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}`);});

test/organisations.test.js added

test/organisations.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('GET /organisations lists organisations with building counts', async () => {  const res = await request(app).get('/organisations');  assert.equal(res.status, 200);  assert.match(res.text, /Liffey Estates<\/a><\/td>\s*<td>2<\/td>/);  assert.match(res.text, /Harbour Lets/);}); test('GET /organisations/1 shows its buildings, not other organisations\' buildings', async () => {  const res = await request(app).get('/organisations/1');  assert.equal(res.status, 200);  assert.match(res.text, /Dublin Offices/);  assert.match(res.text, /Cork Apartments/);  assert.doesNotMatch(res.text, /Galway Studios/);}); test('POST /organisations validates and creates', async () => {  const bad = await request(app).post('/organisations').type('form').send({ name: ' ' });  assert.equal(bad.status, 400);  assert.match(bad.text, /Name must be between 2 and 100 characters/);   const good = await request(app).post('/organisations').type('form').send({ name: 'Riverside Lettings' });  assert.equal(good.status, 303);  const page = await request(app).get(good.headers.location);  assert.match(page.text, /<h1>Riverside Lettings<\/h1>/);}); test('POST /organisations/:id/edit renames the organisation', async () => {  const res = await request(app).post('/organisations/2/edit').type('form').send({ name: 'Harbour Lets Ltd' });  assert.equal(res.status, 303);  const page = await request(app).get('/organisations/2');  assert.match(page.text, /<h1>Harbour Lets Ltd<\/h1>/);}); test('unknown organisations are 404', async () => {  assert.equal((await request(app).get('/organisations/999')).status, 404);  assert.equal((await request(app).post('/organisations/999/edit').type('form').send({ name: 'Nope' })).status, 404);});

views/organisations/form.ejs added

views/organisations/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">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"><%= organisation ? 'Save changes' : 'Create organisation' %></button>    <a class="btn" href="<%= organisation ? `/organisations/${organisation.id}` : '/organisations' %>">Cancel</a>  </div></form><%- include('../partials/foot') %>

views/organisations/index.ejs added

views/organisations/index.ejs
<%- include('../partials/head') %><div class="page-header">  <h1>Organisations</h1>  <a class="btn btn-primary" href="/organisations/new">New organisation</a></div><table class="data">  <thead><tr><th>Name</th><th>Buildings</th></tr></thead>  <tbody>    <% for (const organisation of organisations) { %>      <tr>        <td><a href="/organisations/<%= organisation.id %>"><%= organisation.name %></a></td>        <td><%= organisation.building_count %></td>      </tr>    <% } %>  </tbody></table><%- include('../partials/foot') %>

views/organisations/show.ejs added

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>  </div></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><%= building.name %></td><td><%= building.issue_count %></td></tr>      <% } %>    </tbody>  </table><% } %><%- include('../partials/foot') %>

views/partials/nav.ejs changed

views/partials/nav.ejs
<header class="site-header">  <div class="container header-inner">    <a class="brand" href="/">Caretaker</a>    <nav class="main-nav" aria-label="Main">      <a href="/issues">Issues</a>      <a href="/organisations">Organisations</a>    </nav>  </div></header>

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/lib/ids.js
src/migrate.js
src/models/buildings.js
src/models/issues.js
src/models/organisations.js
src/routes/issues.js
src/routes/organisations.js
src/seed.js
src/server.js
test/helpers.js
test/issues.test.js
test/organisations.test.js
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.1