Ditch bun
This commit is contained in:
72
src/index.ts
Normal file
72
src/index.ts
Normal file
@@ -0,0 +1,72 @@
|
||||
import type { Express } from "express";
|
||||
import express, { application } from 'express';
|
||||
import Path from 'path';
|
||||
import fsp from 'fs/promises';
|
||||
|
||||
function notStupidParseInt(v: string | undefined): number {
|
||||
return v === undefined ? NaN : parseInt(v);
|
||||
}
|
||||
|
||||
const app: Express = express();
|
||||
const port: number = notStupidParseInt(process.env.PORT) || 8080;
|
||||
const dataPath: string = process.env.CONFIG || Path.join('config', 'config.json');
|
||||
|
||||
app.set('trust proxy', 1);
|
||||
app.set('view engine', 'ejs');
|
||||
app.set('view options', { outputFunctionName: 'echo' });
|
||||
app.use('/assets', express.static('assets', { maxAge: '12m' }));
|
||||
|
||||
let visitCount = JSON.parse((await fsp.readFile(dataPath)).toString())['visits'] as number || 0;
|
||||
|
||||
app.get('/healthcheck', (req, res) => {
|
||||
res.send('Healthy');
|
||||
});
|
||||
|
||||
app.get('/', (req, res) => {
|
||||
console.log(req.headers['user-agent']);
|
||||
res.render('index',
|
||||
{
|
||||
visitCount
|
||||
},
|
||||
function (err, html) {
|
||||
if (!err) {
|
||||
res.send(html);
|
||||
}
|
||||
else {
|
||||
console.error(err);
|
||||
res.status(500).send('Something went wrong. Please try again later.');
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
const sendPixel = (_: express.Request, res: express.Response) => {
|
||||
res.set('Cache-Control', 'private, max-age=31557600'); // one year
|
||||
visitCount++;
|
||||
res.sendFile(Path.join(import.meta.dirname, 'assets', 'images', 'webp', 'cache-me.webp'));
|
||||
}
|
||||
|
||||
app.get('/cache-me.webp', sendPixel);
|
||||
app.get('/cache-me-2.webp', sendPixel);
|
||||
|
||||
app.all('*', (req, res) => {
|
||||
console.log(`404: ${req.url} requested by ${req.ip} "${req.headers['user-agent']}"`);
|
||||
res.redirect('/');
|
||||
});
|
||||
|
||||
const webserver = app.listen(port, () => console.log(`jakehurwitzisabitch.com running on port ${port}`));
|
||||
|
||||
async function saveVisits() {
|
||||
await fsp.writeFile(dataPath, JSON.stringify({
|
||||
visits: visitCount
|
||||
}));
|
||||
}
|
||||
|
||||
let inverval = setInterval(saveVisits, 1800000);
|
||||
|
||||
process.on('SIGTERM', async () => {
|
||||
clearInterval(inverval);
|
||||
console.log('writing visit count...');
|
||||
await saveVisits();
|
||||
console.log('done. shutting down...');
|
||||
webserver.close();
|
||||
});
|
Reference in New Issue
Block a user