68 lines
1.9 KiB
TypeScript
68 lines
1.9 KiB
TypeScript
import type { Express } from "express";
|
|
import express, { application } from 'express';
|
|
import Path from 'path';
|
|
|
|
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'));
|
|
|
|
let visitCount = (await Bun.file(dataPath).json())['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.');
|
|
}
|
|
});
|
|
});
|
|
|
|
app.get('/cache-me.webp', (_, res) => {
|
|
res.set('Cache-Control', 'private, max-age=31557600'); // one year
|
|
visitCount++;
|
|
res.sendFile(Path.join(import.meta.dir, 'assets', 'webp', 'cache-me.webp'));
|
|
});
|
|
|
|
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 Bun.write(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();
|
|
}); |