chore: improve bundling + refactor router (#10)
This commit changes how bundling works, by bundling all routes at once. Static JS assets are now cached immutably. Additionally this PR completly refactors how the router works to make it more modular. This allows users to opt out of the default oak server, and instead create their own.
This commit is contained in:
@@ -0,0 +1,50 @@
|
||||
import { extname, oak } from "./deps.ts";
|
||||
import { Bundler } from "./bundle.ts";
|
||||
import { render } from "./render.ts";
|
||||
import { Page } from "./page.ts";
|
||||
import { BUILD_ID, INTERNAL_PREFIX, JS_PREFIX } from "./constants.ts";
|
||||
|
||||
/** This function installs all routes required by fresh onto an oak router. */
|
||||
export function installRoutes(router: oak.Router, pages: Page[]) {
|
||||
for (const page of pages) {
|
||||
router.get<Record<string, string>>(page.route, (ctx) => {
|
||||
ctx.response.status = 200;
|
||||
ctx.response.type = "html";
|
||||
ctx.response.body = render(page, ctx.params);
|
||||
});
|
||||
}
|
||||
|
||||
const internal = internalRouter(pages);
|
||||
|
||||
router.use(
|
||||
INTERNAL_PREFIX,
|
||||
internal.routes(),
|
||||
internal.allowedMethods(),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a router that contains all fresh routes. Should be mounted at
|
||||
* constants.INTERNAL_PREFIX
|
||||
*/
|
||||
function internalRouter(pages: Page[]): oak.Router {
|
||||
const bundler = new Bundler(pages);
|
||||
|
||||
const router = new oak.Router();
|
||||
|
||||
router.get(`${JS_PREFIX}/${BUILD_ID}/:path*`, async (ctx) => {
|
||||
const path = `/${ctx.params.path}`;
|
||||
const file = await bundler.get(path);
|
||||
if (file) {
|
||||
ctx.response.status = 200;
|
||||
ctx.response.type = extname(path);
|
||||
ctx.response.body = file;
|
||||
ctx.response.headers.set(
|
||||
"Cache-Control",
|
||||
"public, max-age=604800, immutable",
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
return router;
|
||||
}
|
||||
Reference in New Issue
Block a user