Caretaker Express · PostgreSQL · Cedar

Checkpoint · Lesson 3.6

A dashboard, and the CRUD app as a whole: checkpoint files

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

Compare your folder with the reference using Git, if you cloned it: git diff lesson/m03-l06 -- 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';import { buildingsRouter } from './routes/buildings.js';import { inspectionsRouter } from './routes/inspections.js';import { getDashboard } from './models/dashboard.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('/', async (req, res) => {  res.render('dashboard', { title: 'Dashboard', dashboard: await getDashboard() });}); app.use('/issues', issuesRouter);app.use('/organisations', organisationsRouter);app.use('/buildings', buildingsRouter);app.use('/inspections', inspectionsRouter); 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/models/dashboard.js added

src/models/dashboard.js
import { query } from '../db.js';import { listIssues } from './issues.js'; export async function getDashboard() {  const [issueCounts, inspectionCounts, buildings, recent] = await Promise.all([    query(      `SELECT count(*) FILTER (WHERE status <> 'closed')::int AS open_issues,              count(*) FILTER (WHERE status <> 'closed' AND priority IN ('high', 'critical'))::int AS serious_open_issues       FROM issues`,    ),    query("SELECT count(*)::int AS awaiting_approval FROM inspections WHERE status = 'submitted'"),    query(      `SELECT s.id, s.name, o.name AS organisation_name,              count(e.id) FILTER (WHERE e.status <> 'closed')::int AS open_issues,              count(e.id)::int AS total_issues       FROM buildings s       JOIN organisations o ON o.id = s.organisation_id       LEFT JOIN issues e ON e.building_id = s.id       GROUP BY s.id, o.name       ORDER BY o.name, s.name`,    ),    listIssues({ perPage: 5 }),  ]);  return {    ...issueCounts.rows[0],    ...inspectionCounts.rows[0],    buildings: buildings.rows,    recentIssues: recent.issues,  };}

test/dashboard.test.js added

test/dashboard.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('the dashboard counts match the database', async () => {  const res = await request(app).get('/');  assert.equal(res.status, 200);  const { rows } = await pool.query("SELECT count(*)::int AS n FROM issues WHERE status <> 'closed'");  assert.match(res.text, new RegExp(`<h3>Open issues</h3><div class="stat">${rows[0].n}</div>`));  assert.match(res.text, /<h3>Inspections awaiting approval<\/h3><div class="stat">2<\/div>/);}); test('every building appears with its organisation', async () => {  const res = await request(app).get('/');  for (const name of ['Dublin Offices', 'Cork Apartments', 'Galway Studios', 'Limerick House']) {    assert.match(res.text, new RegExp(name));  }});

views/dashboard.ejs added

views/dashboard.ejs
<%- include('partials/head') %><h1>Dashboard</h1><div class="cards">  <div class="card"><h3>Open issues</h3><div class="stat"><%= dashboard.open_issues %></div><p class="muted">open or under investigation</p></div>  <div class="card"><h3>Serious and open</h3><div class="stat"><%= dashboard.serious_open_issues %></div><p class="muted">high or critical priority</p></div>  <div class="card"><h3>Inspections awaiting approval</h3><div class="stat"><%= dashboard.awaiting_approval %></div><p class="muted"><a href="/inspections?status=submitted">review them</a></p></div></div> <h2>Buildings</h2><table class="data">  <thead><tr><th>Building</th><th>Organisation</th><th>Open issues</th><th>All issues</th></tr></thead>  <tbody>    <% for (const building of dashboard.buildings) { %>      <tr>        <td><a href="/buildings/<%= building.id %>"><%= building.name %></a></td>        <td><%= building.organisation_name %></td>        <td><a href="/issues?building=<%= building.id %>&status=open"><%= building.open_issues %></a></td>        <td><%= building.total_issues %></td>      </tr>    <% } %>  </tbody></table> <h2>Recent issues</h2><table class="data">  <thead><tr><th>Title</th><th>Building</th><th>Priority</th><th>Occurred</th></tr></thead>  <tbody>    <% for (const issue of dashboard.recentIssues) { %>      <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><%= formatDate(issue.occurred_at) %></td>      </tr>    <% } %>  </tbody></table><%- 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
migrations/002_create_inspections.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/dashboard.js
src/models/inspections.js
src/models/issues.js
src/models/organisations.js
src/routes/buildings.js
src/routes/inspections.js
src/routes/issues.js
src/routes/organisations.js
src/seed.js
src/server.js
test/buildings.test.js
test/dashboard.test.js
test/helpers.js
test/inspections.test.js
test/issue-list.test.js
test/issues.test.js
test/organisations.test.js
views/buildings/form.ejs
views/buildings/show.ejs
views/dashboard.ejs
views/error.ejs
views/inspections/form.ejs
views/inspections/index.ejs
views/inspections/show.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.6