Skip to content

Commit

Permalink
use connect et al. instead of Express
Browse files Browse the repository at this point in the history
  • Loading branch information
pirxpilot committed Jan 4, 2025
1 parent 08cf552 commit 15d9e3f
Show file tree
Hide file tree
Showing 7 changed files with 115 additions and 261 deletions.
36 changes: 19 additions & 17 deletions app.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
const express = require('express');
const connect = require('@pirxpilot/connect');
const cachifyStatic = require('connect-cachify-static');
const gzip = require('connect-gzip-static');
const http = require('node:http');
Expand All @@ -9,12 +9,13 @@ const plugins = require('./lib/plugins');
const cookieParser = require('cookie-parser');
const logger = require('morgan');
const errorHandler = require('errorhandler');
const renderer = require('connect-renderer');

const app = module.exports = express();
const app = module.exports = connect();


if (!process.env.SITE_URL) {
process.env.SITE_URL = app.get('env') === 'production' ?
process.env.SITE_URL = process.env.NODE_ENV === 'production' ?
'https://liftie.info' :
'http://localhost:3000';
}
Expand All @@ -26,7 +27,7 @@ const {
} = process.env;
const cachify = cachifyStatic(root);

Object.assign(app.locals, {
app.locals = {
min: '.min',
decorateAbout() {},
siteUrl,
Expand All @@ -35,25 +36,26 @@ Object.assign(app.locals, {
og: {
image: `${staticHost || siteUrl}/img/snowflake-512.png`
}
});
app.set('port', process.env.PORT || 3000);
app.set('views', `${__dirname}/views`);
app.engine('jade', require('@pirxpilot/jade-core').__express);
app.set('view engine', 'jade');
};

process.env.PORT ??= 3000;

app.use(renderer(`${__dirname}/views`).engine('jade', require('@pirxpilot/jade-core')));

app.use(logger('dev'));
app.use(cookieParser());
app.use(cachify);
app.use((_req, res, next) => {
cachify.helpers().then(fns => {
res.locals.cachify = fns.cachify;
next();
});
app.use(async (req, res, next) => {
req.app = app;
res.locals ??= {};
const fns = await cachify.helpers();
res.locals.cachify = fns.cachify;
next();
});

app.use(gzip(root));

if (app.get('env') === 'development') {
if (process.env.NODE_ENV !== 'production') {
app.locals.min = '';
app.use(errorHandler());
}
Expand All @@ -78,8 +80,8 @@ app.run = function run() {
process.exit(1);
return;
}
http.createServer(app).listen(app.get('port'), () => {
console.log(`Running on: http://localhost:${app.get('port')}`);
http.createServer(app).listen(process.env.PORT, () => {
console.log(`Running on: http://localhost:${process.env.PORT}`);
});
});
};
Expand Down
10 changes: 5 additions & 5 deletions lib/routes/headers.js
Original file line number Diff line number Diff line change
Expand Up @@ -37,20 +37,20 @@ const reportTo = JSON.stringify({
function csp(_req, res, next) {
const cspNonce = crypto.randomBytes(16).toString('base64');
res.locals.cspNonce = cspNonce;
res.header(CSP_HEADER_NAME, cspPolicy.replace('$random', cspNonce));
res.setHeader(CSP_HEADER_NAME, cspPolicy.replace('$random', cspNonce));
if (CSP_REPORT_URI) {
res.header('Report-To', reportTo);
res.setHeader('Report-To', reportTo);
}
next();
}

function referrer(_req, res, next) {
res.header('Referrer-Policy', 'no-referrer-when-downgrade');
res.setHeader('Referrer-Policy', 'no-referrer-when-downgrade');
next();
}

function feature(_req, res, next) {
res.header('Feature-Policy', `fullscreen 'self'`);
res.setHeader('Feature-Policy', `fullscreen 'self'`);
next();
}

Expand All @@ -68,7 +68,7 @@ function link(_req, res, next) {
}
].map(linkHeader);

res.header('Link', preloadLinks);
res.setHeader('Link', preloadLinks);
next();

function linkHeader({ path, as, type }) {
Expand Down
60 changes: 37 additions & 23 deletions lib/routes/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,9 @@ const canonical = require('./canonical');
const plan = require('./plan');
const serviceWorker = require('./service-worker');
const headers = require('./headers');
const Router = require('@pirxpilot/router');
const parseurl = require('parseurl');
const qs = require('qs');

module.exports = routes;

Expand Down Expand Up @@ -142,11 +145,12 @@ function api(req, res, next) {
return next(err);
}
if (resorts.length !== 1) {
return res.send(404, `Invalid resort name: ${req.params.resort}`);
return res.writeHead(404, `Invalid resort name: ${req.params.resort}`).end();
}
// do not cache API responses
res.header('Cache-Control', 'no-cache, max-age=0, must-revalidate');
res.send(resorts[0]);
res.setHeader('Cache-Control', 'no-cache, max-age=0, must-revalidate');
res.setHeader('Content-Type', 'application/json');
res.end(JSON.stringify(resorts[0]));
});
}

Expand All @@ -155,49 +159,59 @@ function meta(req, res, next) {
if (err) {
return next(err);
}
res.header('Cache-Control', 'public, max-age=86400'); // good for 24hours
res.send(resorts);
res.setHeader('Cache-Control', 'public, max-age=86400'); // good for 24hours
res.setHeader('Content-Type', 'application/json');
res.end(JSON.stringify(resorts));
});
}

function routes(app) {
const router = new Router();

function reqData(req, _res, next) {
req.data = app.data;
next();
}

app.param('tag', (req, res, next, t) => {
router.param('tag', (req, res, next, t) => {
const data = app.data;
const tags = data.tags();
const requested = tags[t]?.members;
if (!requested) {
t = canonical(t);
if (tags[t]) {
// permanent redirect to canonical form of the tag
return res.redirect(301, `/tag/${t}`);
return res
.writeHead( 301, { location: `/tag/${encodeURIComponent(t)}` })
.end();
}
return res.send(404, `Invalid tag name: ${req.params.tag}`);
return res.writeHead(404, `Invalid tag name: ${req.params.tag}`).end();
}
req.requested = requested;
req.tag = tags[t];
res.locals.tag = t;
next();
});

app.get('/', reqData, headers, index, renderResorts);
app.get('/resort/:resort', reqData, headers, index, renderResorts);
app.get('/widget/resort/:resort', reqData, headers, widget, renderResorts);
app.get('/tag/:tag', reqData, headers, tag, renderResorts);
app.get('/stars', reqData, headers, stars, renderResorts);
app.get('/api/resort/:resort', reqData, api);
app.get('/api/meta', reqData, meta);
app.get('/sitemap.xml', reqData, sitemap);
app.get('/about', headers, about);
app.get('/absent', reqData, headers, absent, renderResorts);
app.get('/confused', reqData, headers, confused, renderResorts);
app.get('/closed', reqData, headers, closed, renderResorts);
app.get('/stats/:tag', reqData, headers, stats);
app.get('/stats', reqData, headers, stats);
app.get('/sw.js', serviceWorker);
router.use((req, _res, next) => {
req.query = qs.parse(parseurl(req).query);
next();
});
router.get('/', reqData, headers, index, renderResorts);
router.get('/resort/:resort', reqData, headers, index, renderResorts);
router.get('/widget/resort/:resort', reqData, headers, widget, renderResorts);
router.get('/tag/:tag', reqData, headers, tag, renderResorts);
router.get('/stars', reqData, headers, stars, renderResorts);
router.get('/api/resort/:resort', reqData, api);
router.get('/api/meta', reqData, meta);
router.get('/sitemap.xml', reqData, sitemap);
router.get('/about', headers, about);
router.get('/absent', reqData, headers, absent, renderResorts);
router.get('/confused', reqData, headers, confused, renderResorts);
router.get('/closed', reqData, headers, closed, renderResorts);
router.get('/stats/:tag', reqData, headers, stats);
router.get('/stats', reqData, headers, stats);
router.get('/sw.js', serviceWorker);

app.use(router);
}
4 changes: 2 additions & 2 deletions lib/routes/service-worker.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,8 @@ const DEBUG = NODE_ENV !== 'production';
function renderServiceWorker(_req, res) {
createServiceWorkerScript(res.locals).then(serviceWorkerScript => {
// do not cache service worker
res.header('Cache-Control', 'no-cache, max-age=0, must-revalidate');
res.header('Content-Type', 'text/javascript');
res.setHeader('Cache-Control', 'no-cache, max-age=0, must-revalidate');
res.setHeader('Content-Type', 'text/javascript');
res.write(serviceWorkerScript);
res.end();
});
Expand Down
7 changes: 5 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -27,11 +27,14 @@
"test": "make lint test"
},
"dependencies": {
"@pirxpilot/connect": "^4.0.2",
"@pirxpilot/jade-core": "^1.12.1",
"@pirxpilot/k": "^1.0.0",
"@pirxpilot/router": "^1.0.0",
"@pirxpilot/swipe": "^2.0.2",
"connect-cachify-static": "^4.0.0",
"connect-gzip-static": "^4.0.0",
"connect-renderer": "^0.1.1",
"cookie-parser": "^1.4.3",
"css-select": "~5",
"debounce": "^2.0.0",
Expand All @@ -42,13 +45,13 @@
"el-component": "^1.0.1",
"errorhandler": "^1.5.0",
"esbuild": "^0.24.0",
"express": "^4.16.2",
"htmlparser2": "~10",
"js-cookie": "^3.0.5",
"limiter": "~2.1.0",
"lodash": "^4.16.6",
"morgan": "^1.9.0",
"qs": "^6.3.0",
"parseurl": "^1.3.3",
"qs": "^6.13.1",
"ro-rating": "^1.0.2",
"superagent": "~10.1.0",
"tiny-pager": "^1.0.0",
Expand Down
Loading

0 comments on commit 15d9e3f

Please sign in to comment.