Migrate From Bun to Express

This commit is contained in:
Caileb 2025-05-27 16:00:15 -05:00
parent b525cc0dd0
commit d2c014e744
8 changed files with 3054 additions and 668 deletions

View file

@ -72,24 +72,23 @@ function recordEvent(metric, data = {}) {
}
// Handler for serving the stats HTML UI
async function handleStatsPage(request) {
const url = new URL(request.url);
if (url.pathname !== statsUIPath) return undefined;
async function handleStatsPage(req, res) {
const url = new URL(`${req.protocol}://${req.get('host')}${req.originalUrl}`);
if (url.pathname !== statsUIPath) return false;
try {
const html = await fs.readFile(path.join(__dirname, 'stats.html'), 'utf8');
return new Response(html, {
status: 200,
headers: { 'Content-Type': 'text/html; charset=utf-8' },
});
res.status(200).type('html').send(html);
return true;
} catch (e) {
return new Response('Stats UI not found', { status: 404 });
res.status(404).send('Stats UI not found');
return true;
}
}
// Handler for stats API
async function handleStatsAPI(request) {
const url = new URL(request.url);
if (url.pathname !== statsAPIPath) return undefined;
async function handleStatsAPI(req, res) {
const url = new URL(`${req.protocol}://${req.get('host')}${req.originalUrl}`);
if (url.pathname !== statsAPIPath) return false;
const metric = url.searchParams.get('metric');
const start = parseInt(url.searchParams.get('start') || '0', 10);
const end = parseInt(url.searchParams.get('end') || `${Date.now()}`, 10);
@ -101,23 +100,24 @@ async function handleStatsAPI(request) {
})) {
result.push(value);
}
return new Response(JSON.stringify(result), {
status: 200,
headers: { 'Content-Type': 'application/json' },
});
res.status(200).json(result);
return true;
}
// Middleware for stats plugin
function StatsMiddleware() {
return async (request) => {
// Always serve stats UI and API first, bypassing auth
const pageResp = await handleStatsPage(request);
if (pageResp) return pageResp;
const apiResp = await handleStatsAPI(request);
if (apiResp) return apiResp;
return {
middleware: async (req, res, next) => {
// Always serve stats UI and API first, bypassing auth
const pageHandled = await handleStatsPage(req, res);
if (pageHandled) return;
const apiHandled = await handleStatsAPI(req, res);
if (apiHandled) return;
// For any other routes, do not handle
return undefined;
// For any other routes, do not handle
return next();
}
};
}