← back to NationalPaperHangers
tests/app.js
70 lines
// Shared Express app for tests — identical to server.js but no .listen()
// so supertest can bind its own ephemeral port.
require('dotenv').config();
const express = require('express');
const path = require('path');
const session = require('express-session');
const { pool } = require('../lib/db');
const { attachInstaller } = require('../lib/auth');
const { csrfMiddleware } = require('../lib/csrf');
const segmentImage = require('../lib/segment-image');
const publicRoutes = require('../routes/public');
const authRoutes = require('../routes/auth');
const adminRoutes = require('../routes/admin');
const apiRoutes = require('../routes/api');
const claimRoutes = require('../routes/claim');
const webhookRoutes = require('../routes/webhooks');
const unsubscribeRoutes = require('../routes/unsubscribe');
const app = express();
app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, '..', 'views'));
app.use('/webhooks/stripe', express.raw({ type: 'application/json' }), webhookRoutes);
app.use(express.json({ limit: '512kb' }));
app.use(express.urlencoded({ extended: true, limit: '512kb' }));
app.use(express.static(path.join(__dirname, '..', 'public'), { maxAge: 0 }));
// In-memory session store — no DB writes during tests
app.use(session({
store: new (require('express-session').MemoryStore)(),
secret: 'test-secret',
resave: false,
saveUninitialized: false,
name: 'nph.sid'
}));
app.use((req, res, next) => {
res.locals.publicUrl = 'http://localhost';
res.locals.path = req.path;
res.locals.flash = null;
res.locals.pickSegmentImage = segmentImage.pickSegmentImage;
res.locals.imageAttribution = segmentImage.attributionFor;
res.locals.stripePublishableKey = '';
res.locals.consumer = null;
next();
});
app.use(attachInstaller);
// Mirrors server.js — exposes res.locals.csrfToken so views that embed forms
// (COI request, paper comments, booking) render. GET smoke tests pass through.
app.use(csrfMiddleware);
app.use('/', publicRoutes);
app.use('/', authRoutes);
app.use('/', claimRoutes);
app.use('/unsubscribe', unsubscribeRoutes);
app.use('/admin', adminRoutes);
app.use('/api', apiRoutes);
app.use((req, res) => res.status(404).render('public/404', { title: 'Not Found' }));
app.use((err, req, res, next) => {
res.status(err.status || 500);
if (req.accepts('html')) return res.render('public/error', { title: 'Error', message: err.message });
res.json({ error: err.message });
});
module.exports = app;