-
Notifications
You must be signed in to change notification settings - Fork 7
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat(#60): manual static router for dev mode
- Loading branch information
1 parent
8cc5fd1
commit 827f467
Showing
2 changed files
with
45 additions
and
2 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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.'); | ||
} | ||
}); |