Caretaker Express · PostgreSQL · Cedar

Checkpoint · Lesson 2.5

Connect Express to PostgreSQL: checkpoint files

Git tag in the reference repository
lesson/m02-l05 (commit 6eba359)
Replay result
All steps replayed from an empty folder
Tests at this point
pass (tests 5, pass 5, fail 0)

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

Files changed in this lesson

.env.example changed

.env.example
# Copy this file to .env and adjust if needed. Never commit .env.DATABASE_URL=postgres://caretaker:caretaker_dev_password@localhost:5433/caretakerPORT=3000# Set to 1 to print every SQL statement the app runs.LOG_SQL=0

package.json changed

package.json
{  "name": "caretaker",  "version": "1.0.0",  "description": "",  "scripts": {    "test": "NODE_ENV=test node --env-file=.env --test --test-reporter=spec",    "start": "node --env-file=.env src/server.js",    "dev": "node --env-file=.env --watch src/server.js",    "db:migrate": "node --env-file=.env scripts/migrate.js",    "db:seed": "node --env-file=.env scripts/seed.js"  },  "keywords": [],  "author": "",  "license": "ISC",  "type": "module",  "dependencies": {    "ejs": "7.0.2",    "express": "5.3.0",    "pg": "8.23.1"  },  "devDependencies": {    "supertest": "7.3.2"  }}

src/app.js changed

src/app.js
import express from 'express';import path from 'node:path';import { listIssues, findIssue, createIssue } from './models/issues.js';import { listBuildings } from './models/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 })); const PRIORITIES = ['low', 'medium', 'high', 'critical'];const MAX_INTEGER = 2147483647; // Returns a positive integer that fits a PostgreSQL integer column, or null.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;} 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 });} app.get('/', (req, res) => {  res.redirect('/issues');}); app.get('/issues', async (req, res) => {  const issues = await listIssues();  res.render('issues/index', { title: 'Maintenance issues', issues });}); app.get('/issues/new', async (req, res) => {  await renderIssueForm(res, 200);}); app.post('/issues', async (req, res) => {  const { errors, values } = validateIssue(req.body ?? {});  if (Object.keys(errors).length > 0) {    return renderIssueForm(res, 400, { values, errors });  }  const issue = await createIssue(values);  res.redirect(303, `/issues/${issue.id}`);}); app.get('/issues/: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.path });  }  res.render('issues/show', { title: issue.title, issue });}); app.use((req, res) => {  res.status(404).render('not-found', { title: 'Not found', path: req.path });}); 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/config.js added

src/config.js
function required(name) {  const value = process.env[name];  if (!value) {    throw new Error(`Missing required environment variable ${name}. Copy .env.example to .env.`);  }  return value;} export const config = {  port: Number(process.env.PORT ?? 3000),  databaseUrl: required('DATABASE_URL'),  logSql: process.env.LOG_SQL === '1',};

src/db.js added

src/db.js
import pg from 'pg';import { config } from './config.js'; export const pool = new pg.Pool({ connectionString: config.databaseUrl, max: 10 }); export async function query(text, params = []) {  const started = Date.now();  const result = await pool.query(text, params);  if (config.logSql) {    console.log(`SQL ${Date.now() - started}ms ${text.replace(/\s+/g, ' ').trim()} ${JSON.stringify(params)}`);  }  return result;}

src/models/buildings.js added

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

src/models/issues.js added

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 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/server.js changed

src/server.js
import { app } from './app.js';import { config } from './config.js'; app.listen(config.port, () => {  console.log(`Caretaker listening on http://localhost:${config.port}`);});

test/issues.test.js changed

test/issues.test.js
import { test, 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'; after(() => pool.end()); 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: '' });  assert.equal(res.status, 400);  assert.match(res.text, /Choose a building/);}); test('POST /issues stores the issue and redirects to it', async () => {  const res = await request(app)    .post('/issues')    .type('form')    .send({ title: 'Water leak by the staff entrance', building_id: '10', priority: 'low' });  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/);});

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> <% if (issues.length === 0) { %>  <p class="empty">No issues yet.</p><% } else { %>  <table class="data">    <thead>      <tr><th>Title</th><th>Building</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><%= 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><% } %><%- include('../partials/foot') %>

views/issues/new.ejs changed

views/issues/new.ejs
<%- include('../partials/head') %><h1>Report a maintenance issue</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="/issues" 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.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>   <div class="form-actions">    <button type="submit" class="btn btn-primary">Save issue</button>    <a class="btn" href="/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><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) %></dd></dl><% if (issue.description) { %>  <h2>Description</h2>  <p class="prose"><%= issue.description %></p><% } %><%- include('../partials/foot') %>

Project tree at this checkpoint

.env.example
.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/migrate.js
src/models/buildings.js
src/models/issues.js
src/seed.js
src/server.js
test/issues.test.js
views/error.ejs
views/issues/index.ejs
views/issues/new.ejs
views/issues/show.ejs
views/not-found.ejs
views/partials/foot.ejs
views/partials/head.ejs
views/partials/nav.ejs

Back to lesson 2.5