Caretaker Express · PostgreSQL · Cedar

Checkpoint · Lesson 1.5

First tests, and the limits of memory: checkpoint files

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

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

Files changed in this lesson

package-lock.json changed

Generated by npm from package.json. Do not edit it by hand; run the npm commands from the lesson.

package.json changed

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

src/app.js added

src/app.js
import express from 'express';import path from 'node:path'; export const app = express(); app.set('view engine', 'ejs');app.set('views', path.join(import.meta.dirname, '..', 'views'));app.locals.formatDate = (iso) => new Date(iso).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.json());app.use(express.urlencoded({ extended: false })); const issues = [  { id: 1, title: 'Lift stuck between floors 2 and 3', priority: 'high', status: 'open', building: 'Dublin Offices', occurredAt: '2026-11-02T09:15:00.000Z' },  { id: 2, title: 'Dripping tap in the second-floor kitchen', priority: 'medium', status: 'closed', building: 'Dublin Offices', occurredAt: '2026-11-05T14:40:00.000Z' },  { id: 3, title: 'Front door lock sticks at entrance 4', priority: 'critical', status: 'open', building: 'Cork Apartments', occurredAt: '2026-11-08T07:05:00.000Z' },]; const PRIORITIES = ['low', 'medium', 'high', 'critical']; function validateIssue(input) {  const errors = {};  const title = typeof input.title === 'string' ? input.title.trim() : '';  const building = typeof input.building === 'string' ? input.building.trim() : '';  if (title.length < 3 || title.length > 200) {    errors.title = 'Title must be between 3 and 200 characters.';  }  if (!PRIORITIES.includes(input.priority)) {    errors.priority = `Priority must be one of: ${PRIORITIES.join(', ')}.`;  }  if (building.length === 0) {    errors.building = 'Building is required.';  }  return { errors, values: { title, priority: input.priority, building } };} app.get('/', (req, res) => {  res.redirect('/issues');}); app.get('/api/issues', (req, res) => {  const { status } = req.query;  const result = status ? issues.filter((issue) => issue.status === status) : issues;  res.json(result);}); app.get('/api/issues/:id', (req, res) => {  const id = Number(req.params.id);  const issue = issues.find((e) => e.id === id);  if (!issue) {    return res.status(404).json({ error: 'Issue not found' });  }  res.json(issue);}); let nextId = 4; app.post('/api/issues', (req, res) => {  const { errors, values } = validateIssue(req.body ?? {});  if (Object.keys(errors).length > 0) {    return res.status(400).json({ errors });  }  const issue = { id: nextId++, ...values, status: 'open', occurredAt: new Date().toISOString() };  issues.push(issue);  res.status(201).location(`/api/issues/${issue.id}`).json(issue);}); app.get('/issues', (req, res) => {  res.render('issues/index', { title: 'Maintenance issues', issues });}); app.get('/issues/new', (req, res) => {  res.render('issues/new', { title: 'Report an issue', values: {}, errors: {}, priorities: PRIORITIES });}); app.post('/issues', (req, res) => {  const { errors, values } = validateIssue(req.body ?? {});  if (Object.keys(errors).length > 0) {    return res.status(400).render('issues/new', { title: 'Report an issue', values, errors, priorities: PRIORITIES });  }  const issue = { id: nextId++, ...values, status: 'open', occurredAt: new Date().toISOString() };  issues.push(issue);  res.redirect(303, `/issues/${issue.id}`);}); app.get('/issues/:id', (req, res) => {  const issue = issues.find((e) => e.id === Number(req.params.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) => {  if (req.path.startsWith('/api/')) {    return res.status(404).json({ error: `No route for ${req.method} ${req.path}` });  }  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';  if (req.path.startsWith('/api/')) {    return res.status(status).json({ error: message });  }  res.status(status).render('error', { title: 'Error', status, message });});

src/server.js changed

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

test/issues.test.js added

test/issues.test.js
import { test } from 'node:test';import assert from 'node:assert/strict';import request from 'supertest';import { app } from '../src/app.js'; test('GET /api/issues lists the starting issues as JSON', async () => {  const res = await request(app).get('/api/issues');  assert.equal(res.status, 200);  assert.match(res.headers['content-type'], /application\/json/);  assert.equal(res.body.length, 3);  assert.equal(res.body[0].title, 'Lift stuck between floors 2 and 3');}); test('GET /api/issues/:id returns 404 JSON for an unknown id', async () => {  const res = await request(app).get('/api/issues/99');  assert.equal(res.status, 404);  assert.deepEqual(res.body, { error: 'Issue not found' });}); test('POST /api/issues rejects invalid input with field errors', async () => {  const res = await request(app).post('/api/issues').send({ title: 'Hi', priority: 'extreme' });  assert.equal(res.status, 400);  assert.ok(res.body.errors.title);  assert.ok(res.body.errors.priority);  assert.ok(res.body.errors.building);}); test('POST /api/issues creates an issue', async () => {  const res = await request(app)    .post('/api/issues')    .send({ title: 'Broken light in stairwell B', priority: 'low', building: 'Cork Apartments' });  assert.equal(res.status, 201);  assert.match(res.headers.location, /^\/api\/issues\/\d+$/);  assert.equal(res.body.status, 'open');}); test('GET /issues renders the list page', async () => {  const res = await request(app).get('/issues');  assert.equal(res.status, 200);  assert.match(res.text, /<h1>Maintenance issues<\/h1>/);  assert.match(res.text, /Lift stuck between floors 2 and 3/);}); test('POST /issues re-renders the form with errors', async () => {  const res = await request(app).post('/issues').type('form').send({ title: '', building: '', priority: '' });  assert.equal(res.status, 400);  assert.match(res.text, /Title must be between 3 and 200 characters/);}); test('POST /issues redirects to the new issue (Post/Redirect/Get)', async () => {  const res = await request(app)    .post('/issues')    .type('form')    .send({ title: 'Water leak by the staff entrance', building: 'Dublin Offices', priority: 'low' });  assert.equal(res.status, 303);  assert.match(res.headers.location, /^\/issues\/\d+$/);});

Project tree at this checkpoint

.gitignore
.npmrc
package-lock.json
package.json
public/css/style.css
src/app.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 1.5