Caretaker Express · PostgreSQL · Cedar

Checkpoint · Lesson 3.3

Edit, move and delete issues: checkpoint files

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

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

Files changed in this lesson

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, occurred_at }) {  const { rows } = await query(    `INSERT INTO issues (building_id, title, description, priority, occurred_at)     VALUES ($1, $2, $3, $4, $5)     RETURNING id`,    [building_id, title, description, priority, occurred_at],  );  return rows[0];} export async function updateIssue(id, { building_id, title, description, priority, status, occurred_at }) {  const { rows } = await query(    `UPDATE issues     SET building_id = $2, title = $3, description = $4, priority = $5, status = $6, occurred_at = $7, updated_at = now()     WHERE id = $1     RETURNING id`,    [id, building_id, title, description, priority, status, occurred_at],  );  return rows[0] ?? null;} export async function deleteIssue(id) {  const { rowCount } = await query('DELETE FROM issues WHERE id = $1', [id]);  return rowCount === 1;}

src/routes/issues.js changed

src/routes/issues.js
import express from 'express';import { listIssues, findIssue, createIssue, updateIssue, deleteIssue } from '../models/issues.js';import { listBuildings } from '../models/buildings.js';import { PG_ERRORS } from '../db.js';import { parseId } from '../lib/ids.js';import { cleanText } from '../lib/validation.js'; export const issuesRouter = express.Router(); export const PRIORITIES = ['low', 'medium', 'high', 'critical'];export const STATUSES = ['open', 'investigating', 'closed'];const FIVE_MINUTES = 5 * 60 * 1000; // <input type="datetime-local"> sends "2026-11-02T09:15" without a time zone. We treat it as UTC.function parseDateTimeLocal(value) {  if (typeof value !== 'string' || !/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}$/.test(value)) {    return null;  }  const date = new Date(`${value}:00Z`);  return Number.isNaN(date.getTime()) ? null : date;} // The reverse: a Date as "YYYY-MM-DDTHH:MM" in UTC, for the input's value attribute.function toDateTimeLocal(date) {  return new Date(date).toISOString().slice(0, 16);} function validateIssue(input, { editing }) {  const errors = {};  const title = cleanText(input.title, { min: 3, max: 200 });  const description = cleanText(input.description, { max: 2000 });  const buildingId = parseId(input.building_id);  const occurredAt = parseDateTimeLocal(input.occurred_at);  const status = editing ? input.status : 'open';  if (!title.ok) {    errors.title = 'Title must be between 3 and 200 characters.';  }  if (!description.ok) {    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.';  }  if (!occurredAt) {    errors.occurred_at = 'Enter the date and time it happened (UTC).';  } else if (occurredAt.getTime() > Date.now() + FIVE_MINUTES) {    errors.occurred_at = 'That time is in the future.';  }  if (!STATUSES.includes(status)) {    errors.status = `Status must be one of: ${STATUSES.join(', ')}.`;  }  // values: what the form shows again. record: what we store.  const values = {    title: title.text,    description: description.text,    priority: input.priority,    building_id: buildingId,    status,    occurred_at: typeof input.occurred_at === 'string' ? input.occurred_at : '',  };  const record = { ...values, occurred_at: occurredAt };  return { errors, values, record };} async function renderIssueForm(res, status, { issue = null, values = {}, errors = {} } = {}) {  const buildings = await listBuildings();  res.status(status).render('issues/form', {    title: issue ? `Edit issue #${issue.id}` : 'Report an issue',    action: issue ? `/issues/${issue.id}/edit` : '/issues',    issue,    values,    errors,    buildings,    priorities: PRIORITIES,    statuses: STATUSES,  });} async function loadIssue(req, res) {  const id = parseId(req.params.id);  const issue = id === null ? null : await findIssue(id);  if (!issue) {    res.status(404).render('not-found', { title: 'Not found', path: req.originalUrl });    return null;  }  return issue;} 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, { values: { occurred_at: toDateTimeLocal(new Date()) } });}); issuesRouter.post('/', async (req, res) => {  const { errors, values, record } = validateIssue(req.body ?? {}, { editing: false });  if (Object.keys(errors).length > 0) {    return renderIssueForm(res, 400, { values, errors });  }  let created;  try {    created = await createIssue(record);  } 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/${created.id}`);}); issuesRouter.get('/:id', async (req, res) => {  const issue = await loadIssue(req, res);  if (!issue) return;  res.render('issues/show', { title: issue.title, issue });}); issuesRouter.get('/:id/edit', async (req, res) => {  const issue = await loadIssue(req, res);  if (!issue) return;  await renderIssueForm(res, 200, { issue, values: { ...issue, occurred_at: toDateTimeLocal(issue.occurred_at) } });}); issuesRouter.post('/:id/edit', async (req, res) => {  const issue = await loadIssue(req, res);  if (!issue) return;  const { errors, values, record } = validateIssue(req.body ?? {}, { editing: true });  if (Object.keys(errors).length > 0) {    return renderIssueForm(res, 400, { issue, values, errors });  }  try {    await updateIssue(issue.id, record);  } catch (err) {    if (err.code === PG_ERRORS.FOREIGN_KEY_VIOLATION) {      return renderIssueForm(res, 400, { issue, values, errors: { building_id: 'Choose a building.' } });    }    throw err;  }  res.redirect(303, `/issues/${issue.id}`);}); issuesRouter.post('/:id/delete', async (req, res) => {  const issue = await loadIssue(req, res);  if (!issue) return;  await deleteIssue(issue.id);  res.redirect(303, '/issues');});

test/issues.test.js changed

test/issues.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()); const validIssue = { title: 'Water leak by the staff entrance', building_id: '10', priority: 'low', occurred_at: '2026-11-20T10:30' }; 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: '', occurred_at: '' });  assert.equal(res.status, 400);  assert.match(res.text, /Choose a building/);  assert.match(res.text, /Enter the date and time it happened/);}); test('POST /issues stores the issue and redirects to it', async () => {  const res = await request(app).post('/issues').type('form').send(validIssue);  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/);  assert.match(page.text, /20 Nov 2026, 10:30 UTC/);}); 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({ ...validIssue, building_id: '999' });  assert.equal(res.status, 400);  assert.match(res.text, /Choose a building/);}); test('the stored row has the cleaned values and ignores a client-sent status', async () => {  await request(app).post('/issues').type('form').send({ ...validIssue, title: '  Spaces around  ', building_id: '20', 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' }]);}); test('an issue time in the future is rejected', async () => {  const res = await request(app).post('/issues').type('form').send({ ...validIssue, occurred_at: '2099-01-01T00:00' });  assert.equal(res.status, 400);  assert.match(res.text, /That time is in the future/);}); test('GET /issues/101/edit shows the current values', async () => {  const res = await request(app).get('/issues/101/edit');  assert.equal(res.status, 200);  assert.match(res.text, /value="2026-11-02T09:15"/);  assert.match(res.text, /<option value="open" selected>open<\/option>/);}); test('POST /issues/:id/edit changes the status and updated_at', async () => {  const before = (await pool.query('SELECT updated_at FROM issues WHERE id = 103')).rows[0].updated_at;  const res = await request(app).post('/issues/103/edit').type('form')    .send({ title: 'Front door lock sticks at entrance 4', building_id: '20', priority: 'medium', status: 'investigating', occurred_at: '2026-11-08T07:05' });  assert.equal(res.status, 303);  const { rows } = await pool.query('SELECT status, updated_at FROM issues WHERE id = 103');  assert.equal(rows[0].status, 'investigating');  assert.ok(rows[0].updated_at > before);}); test('POST /issues/:id/delete removes the issue', async () => {  const created = await request(app).post('/issues').type('form').send({ ...validIssue, title: 'Delete me please' });  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/issues/form.ejs renamed

views/issues/form.ejs
<%- include('../partials/head') %><h1><%= title %></h1> <% if (Object.keys(errors).length > 0) { %>  <div class="error-summary" role="alert">    <p>Please fix the highlighted fields.</p>  </div><% } %> <form method="post" action="<%= action %>" class="form" novalidate>  <div class="field<%= errors.title ? ' has-error' : '' %>">    <label for="title">Title</label>    <input id="title" name="title" value="<%= values.title ?? '' %>" maxlength="200" required>    <% if (errors.title) { %><p class="field-error"><%= errors.title %></p><% } %>  </div>   <div class="field<%= errors.building_id ? ' has-error' : '' %>">    <label for="building_id">Building</label>    <select id="building_id" name="building_id">      <option value="">Choose…</option>      <% for (const building of buildings) { %>        <option value="<%= building.id %>"<%= values.building_id === building.id ? ' selected' : '' %>><%= building.organisation_name %> · <%= building.name %></option>      <% } %>    </select>    <% if (errors.building_id) { %><p class="field-error"><%= errors.building_id %></p><% } %>  </div>   <div class="field<%= errors.occurred_at ? ' has-error' : '' %>">    <label for="occurred_at">Occurred at (UTC)</label>    <input id="occurred_at" name="occurred_at" type="datetime-local" value="<%= values.occurred_at ?? '' %>">    <% if (errors.occurred_at) { %><p class="field-error"><%= errors.occurred_at %></p><% } %>  </div>   <div class="field<%= errors.description ? ' has-error' : '' %>">    <label for="description">Description <span class="muted">(optional)</span></label>    <textarea id="description" name="description" maxlength="2000"><%= values.description ?? '' %></textarea>    <% if (errors.description) { %><p class="field-error"><%= errors.description %></p><% } %>  </div>   <div class="field<%= errors.priority ? ' has-error' : '' %>">    <label for="priority">Priority</label>    <select id="priority" name="priority">      <option value="">Choose…</option>      <% for (const s of priorities) { %>        <option value="<%= s %>"<%= values.priority === s ? ' selected' : '' %>><%= s %></option>      <% } %>    </select>    <% if (errors.priority) { %><p class="field-error"><%= errors.priority %></p><% } %>  </div>   <% if (issue) { %>    <div class="field<%= errors.status ? ' has-error' : '' %>">      <label for="status">Status</label>      <select id="status" name="status">        <% for (const s of statuses) { %>          <option value="<%= s %>"<%= values.status === s ? ' selected' : '' %>><%= s %></option>        <% } %>      </select>      <% if (errors.status) { %><p class="field-error"><%= errors.status %></p><% } %>    </div>  <% } %>   <div class="form-actions">    <button type="submit" class="btn btn-primary"><%= issue ? 'Save changes' : 'Save issue' %></button>    <a class="btn" href="<%= issue ? `/issues/${issue.id}` : '/issues' %>">Cancel</a>  </div></form><%- include('../partials/foot') %>

views/issues/show.ejs changed

views/issues/show.ejs
<%- include('../partials/head') %><p class="breadcrumbs"><a href="/issues">Issues</a> / #<%= issue.id %></p><div class="page-header">  <h1><%= issue.title %></h1>  <div class="actions">    <a class="btn" href="/issues/<%= issue.id %>/edit">Edit</a>    <form method="post" action="/issues/<%= issue.id %>/delete" data-confirm="Delete this issue? This cannot be undone.">      <button type="submit" class="btn btn-danger">Delete</button>    </form>  </div></div><dl class="details">  <dt>Building</dt><dd><%= issue.building_name %></dd>  <dt>Priority</dt><dd><span class="badge sev-<%= issue.priority %>"><%= issue.priority %></span></dd>  <dt>Status</dt><dd><span class="badge status-<%= issue.status %>"><%= issue.status %></span></dd>  <dt>Occurred</dt><dd><%= formatDate(issue.occurred_at) %> UTC</dd>  <dt>Last updated</dt><dd><%= formatDate(issue.updated_at) %> UTC</dd></dl><% if (issue.description) { %>  <h2>Description</h2>  <p class="prose"><%= issue.description %></p><% } %><%- include('../partials/foot') %>

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/form.ejs
views/issues/index.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.3