Skip to content

Commit

Permalink
feat(#60): manual static router for dev mode
Browse files Browse the repository at this point in the history
  • Loading branch information
jannis-baum committed Jul 4, 2024
1 parent 8cc5fd1 commit 827f467
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 2 deletions.
4 changes: 2 additions & 2 deletions src/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,12 @@ export const registerAsyncInit = (f: () => Promise<void>) => {
};

import { createServer } from 'http';
import path from 'path';

import express from 'express';

import { router as healthRouter } from './routes/health';
import { router as viewerRouter } from './routes/viewer';
import { router as staticRouter } from './routes/static';
import { setupSockets } from './sockets';
import { urlToPath } from './utils/path';

Expand All @@ -24,7 +24,7 @@ app.use((req, res, next) => {
res.locals.filepath = urlToPath(req.path);
next();
});
app.use('/static', express.static(path.join(__dirname, '../static')));
app.use('/static', staticRouter);
app.use('/health', healthRouter);
app.use('/viewer', viewerRouter);

Expand Down
43 changes: 43 additions & 0 deletions src/routes/static.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import { Router } from 'express';
import { readFile } from 'fs/promises';
import { dirname as pdirname, join as pjoin } from 'path';

export const router = Router();

class StaticProvider {
private static instance = new StaticProvider();

private _content: (path: string) => Promise<Buffer>;

private constructor() {
this._content = (path) =>
this._contentDev(pjoin(pdirname(pdirname(__dirname)), 'static'), path);
}

private async _contentDev(staticDir: string, path: string): Promise<Buffer> {
return readFile(pjoin(staticDir, path));
}

static async content(path: string): Promise<Buffer> {
return StaticProvider.instance._content(path);
}

static mime(path: string): string {
if (path.endsWith('.css')) return 'text/css';
if (path.endsWith('.js')) return 'text/javascript';
if (path.endsWith('.ttf')) return 'font/ttf';
if (path.endsWith('.woff2')) return 'font/woff2';
throw new Error('Unknown MIME type');
}
}

router.get(/.*/, async (req, res) => {
const path = req.path;

try {
res.type(StaticProvider.mime(path));
res.send(await StaticProvider.content(path));
} catch {
res.status(404).send('File not found.');
}
});

0 comments on commit 827f467

Please sign in to comment.