Caretaker Express · PostgreSQL · Cedar

Checkpoint · Lesson 3.4

Paging, sorting and filtering: checkpoint files

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

Compare your folder with the reference using Git, if you cloned it: git diff lesson/m03-l04 -- 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`; // Sort keys a client may ask for. Keys come from the URL; the SQL is ours.export const ISSUE_SORTS = {  occurred_at: 'e.occurred_at',  title: 'e.title',  building: 's.name',  priority: "array_position(ARRAY['low', 'medium', 'high', 'critical'], e.priority)",  status: "array_position(ARRAY['open', 'investigating', 'closed'], e.status)",}; export async function listIssues({ page = 1, perPage = 10, sort = 'occurred_at', dir = 'desc', status = null, priority = null, buildingId = null } = {}) {  const where = [];  const params = [];  if (status) {    params.push(status);    where.push(`e.status = $${params.length}`);  }  if (priority) {    params.push(priority);    where.push(`e.priority = $${params.length}`);  }  if (buildingId) {    params.push(buildingId);    where.push(`e.building_id = $${params.length}`);  }  const whereSql = where.length > 0 ? `WHERE ${where.join(' AND ')}` : '';  const direction = dir === 'asc' ? 'ASC' : 'DESC';  const orderSql = `${ISSUE_SORTS[sort] ?? ISSUE_SORTS.occurred_at} ${direction}, e.id ${direction}`;   const countResult = await query(    `SELECT count(*)::int AS total FROM issues e JOIN buildings s ON s.id = e.building_id ${whereSql}`,    params,  );  const { rows } = await query(    `SELECT ${ISSUE_COLUMNS}     FROM issues e     JOIN buildings s ON s.id = e.building_id     ${whereSql}     ORDER BY ${orderSql}     LIMIT $${params.length + 1} OFFSET $${params.length + 2}`,    [...params, perPage, (page - 1) * perPage],  );  return { issues: rows, total: countResult.rows[0].total };} 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, ISSUE_SORTS } 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,  });} const PER_PAGE = 10; // Converts the query string into list options. Invalid values become defaults.function parseListQuery(query) {  const page = parseId(query.page) ?? 1;  return {    page,    sort: Object.hasOwn(ISSUE_SORTS, query.sort) ? query.sort : 'occurred_at',    dir: query.dir === 'asc' ? 'asc' : 'desc',    status: STATUSES.includes(query.status) ? query.status : null,    priority: PRIORITIES.includes(query.priority) ? query.priority : null,    building: parseId(query.building),  };} // Builds a /issues URL from the current options plus overrides, dropping defaults.function listUrl(options, overrides = {}) {  const merged = { ...options, ...overrides };  const params = new URLSearchParams();  for (const [key, value] of Object.entries(merged)) {    const isDefault = value === null || (key === 'page' && value === 1) || (key === 'sort' && value === 'occurred_at') || (key === 'dir' && value === 'desc');    if (!isDefault) params.set(key, String(value));  }  const qs = params.toString();  return qs ? `/issues?${qs}` : '/issues';} 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 options = parseListQuery(req.query);  const { issues, total } = await listIssues({ ...options, buildingId: options.building, perPage: PER_PAGE });  const buildings = await listBuildings();  res.render('issues/index', {    title: 'Maintenance issues',    issues,    total,    options,    buildings,    priorities: PRIORITIES,    statuses: STATUSES,    totalPages: Math.max(1, Math.ceil(total / PER_PAGE)),    listUrl: (overrides) => listUrl(options, overrides),  });}); 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/issue-list.test.js added

test/issue-list.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()); // The issue ids linked from the table rows, in order.function issueIds(html) {  return [...html.matchAll(/<td><a href="\/issues\/(\d+)">/g)].map((m) => Number(m[1]));} test('the list pages 10 at a time and reports the total', async () => {  const first = await request(app).get('/issues');  assert.equal(issueIds(first.text).length, 10);  assert.match(first.text, /30 issues/);  const third = await request(app).get('/issues?page=3');  assert.equal(issueIds(third.text).length, 10);  const fourth = await request(app).get('/issues?page=4');  assert.equal(issueIds(fourth.text).length, 0);}); test('pages do not overlap', async () => {  const ids = [];  for (const page of [1, 2, 3]) ids.push(...issueIds((await request(app).get(`/issues?page=${page}`)).text));  assert.equal(new Set(ids).size, 30);}); test('filters combine with AND', async () => {  const res = await request(app).get('/issues?status=open&building=20');  const ids = issueIds(res.text);  assert.ok(ids.length > 0);  const { rows } = await pool.query('SELECT id FROM issues WHERE status = $1 AND building_id = $2', ['open', 20]);  assert.deepEqual(new Set(ids), new Set(rows.map((r) => r.id)));}); test('sorting by priority puts critical first when descending', async () => {  const res = await request(app).get('/issues?sort=priority&dir=desc');  assert.match(res.text, /<span class="badge sev-critical">/);  const firstBadge = res.text.match(/class="badge sev-(\w+)"/)[1];  assert.equal(firstBadge, 'critical');}); test('unknown sort keys and SQL in the query string are ignored', async () => {  for (const qs of ['sort=(SELECT%201/0)', 'sort=toString', 'dir=sideways', 'page=-1', 'status=%27%3B--', 'building=abc']) {    const res = await request(app).get(`/issues?${qs}`);    assert.equal(res.status, 200, qs);    assert.equal(issueIds(res.text).length, 10, qs);  }});

views/issues/index.ejs changed

views/issues/index.ejs
<%- include('../partials/head') %><div class="page-header">  <h1>Maintenance issues</h1>  <a class="btn btn-primary" href="/issues/new">Report an issue</a></div> <form method="get" action="/issues" class="filters">  <label>Status    <select name="status">      <option value="">Any</option>      <% for (const s of statuses) { %><option value="<%= s %>"<%= options.status === s ? ' selected' : '' %>><%= s %></option><% } %>    </select>  </label>  <label>Priority    <select name="priority">      <option value="">Any</option>      <% for (const s of priorities) { %><option value="<%= s %>"<%= options.priority === s ? ' selected' : '' %>><%= s %></option><% } %>    </select>  </label>  <label>Building    <select name="building">      <option value="">Any</option>      <% for (const building of buildings) { %><option value="<%= building.id %>"<%= options.building === building.id ? ' selected' : '' %>><%= building.organisation_name %> · <%= building.name %></option><% } %>    </select>  </label>  <input type="hidden" name="sort" value="<%= options.sort %>">  <input type="hidden" name="dir" value="<%= options.dir %>">  <button type="submit" class="btn btn-small">Apply</button>  <a class="btn btn-small" href="/issues">Reset</a></form> <%  const columns = [['title', 'Title'], ['building', 'Building'], ['priority', 'Priority'], ['status', 'Status'], ['occurred_at', 'Occurred']];  const arrow = (key) => (options.sort === key ? (options.dir === 'asc' ? ' ▲' : ' ▼') : '');  const nextDir = (key) => (options.sort === key && options.dir === 'desc' ? 'asc' : 'desc');%><p class="muted"><%= total %> issue<%= total === 1 ? '' : 's' %></p><% if (issues.length === 0) { %>  <p class="empty">No issues match these filters.</p><% } else { %>  <table class="data">    <thead>      <tr>        <% for (const [key, label] of columns) { %>          <th><a href="<%= listUrl({ sort: key, dir: nextDir(key), page: 1 }) %>"><%= label %><%= arrow(key) %></a></th>        <% } %>      </tr>    </thead>    <tbody>      <% for (const issue of issues) { %>        <tr>          <td><a href="/issues/<%= issue.id %>"><%= issue.title %></a></td>          <td><%= issue.building_name %></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><% } %> <nav class="pagination" aria-label="Pages">  <% if (options.page > 1) { %><a href="<%= listUrl({ page: options.page - 1 }) %>">← Previous</a><% } %>  <% for (let p = 1; p <= totalPages; p++) { %>    <% if (p === options.page) { %><span class="current" aria-current="page"><%= p %></span><% } else { %><a href="<%= listUrl({ page: p }) %>"><%= p %></a><% } %>  <% } %>  <% if (options.page < totalPages) { %><a href="<%= listUrl({ page: options.page + 1 }) %>">Next →</a><% } %></nav><%- 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/issue-list.test.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.4