refactor: centralize server into ServerContext (#26)

This commit centralizes all server related logic into a central
ServerContext class.
This commit is contained in:
Luca Casonato
2021-06-10 20:46:10 +02:00
committed by GitHub
parent 78c144641c
commit 572b8123c4
9 changed files with 236 additions and 224 deletions
+181
View File
@@ -0,0 +1,181 @@
import { extname, mediaTypeLookup, router } from "./deps.ts";
import * as rt from "../runtime/deps.ts";
import { PageProps } from "../runtime/types.ts";
import { Routes } from "./mod.ts";
import { Bundler } from "./bundle.ts";
import { INTERNAL_PREFIX } from "./constants.ts";
import { JS_PREFIX } from "./constants.ts";
import { BUILD_ID } from "./constants.ts";
import { ApiRoute, Page } from "./types.ts";
import { render } from "./render.ts";
export class ServerContext {
#pages: Page[];
#apiRoutes: ApiRoute[];
#bundler: Bundler;
constructor(pages: Page[], apiRoutes: ApiRoute[]) {
this.#pages = pages;
this.#apiRoutes = apiRoutes;
this.#bundler = new Bundler(pages);
}
/**
* Process the routes into individual components and pages.
*/
static fromRoutes(routes: Routes): ServerContext {
// Get the routes' base URL.
const baseUrl = new URL("./", routes.baseUrl).href;
// Extract all pages, and prepare them into this `Page` structure.
const pages: Page[] = [];
const apiRoutes: ApiRoute[] = [];
for (const [self, module] of Object.entries(routes.pages)) {
const url = new URL(self, baseUrl).href;
if (!url.startsWith(baseUrl)) {
throw new TypeError("Page is not a child of the basepath.");
}
const path = url.substring(baseUrl.length).substring("pages".length);
const baseRoute = path.substring(1, path.length - extname(path).length);
const route = pathToRoute(baseRoute);
const name = baseRoute.replace("/", "-");
if (path.startsWith("/api/")) {
const apiRoute: ApiRoute = {
route,
url,
name,
handler: module.default as router.MatchHandler,
};
apiRoutes.push(apiRoute);
} else if (!path.startsWith("/_")) {
const page: Page = {
route,
url,
name,
component: module.default as rt.ComponentType<PageProps>,
};
pages.push(page);
}
}
sortRoutes(pages);
sortRoutes(apiRoutes);
return new ServerContext(pages, apiRoutes);
}
/**
* This function returns all routes required by fresh as an extended
* path-to-regex, to handler mapping.
*/
routes(): router.Routes {
const routes: router.Routes = {};
for (const page of this.#pages) {
const bundlePath = `/${page.name}.js`;
const imports = [bundleAssetUrl(bundlePath)];
routes[page.route] = (_, match) => {
const preloads = this.#bundler.getPreloads(bundlePath).map(
bundleAssetUrl,
);
const body = render({
page,
imports,
preloads,
params: match.params,
});
return new Response(body, {
status: 200,
headers: {
"content-type": "text/html; charset=utf-8",
},
});
};
}
for (const apiRoute of this.#apiRoutes) {
routes[apiRoute.route] = apiRoute.handler;
}
routes[`${INTERNAL_PREFIX}${JS_PREFIX}/${BUILD_ID}/:path*`] = this
.#bundleAssetRoute();
return routes;
}
/**
* Returns a router that contains all fresh routes. Should be mounted at
* constants.INTERNAL_PREFIX
*/
#bundleAssetRoute = (): router.MatchHandler => {
return async (_req, match) => {
const path = `/${match.params.path}`;
const file = await this.#bundler.get(path);
let res;
if (file) {
const headers = new Headers({
"Cache-Control": "public, max-age=604800, immutable",
});
const contentType = mediaTypeLookup(path);
if (contentType) {
headers.set("Content-Type", contentType);
}
res = new Response(file, {
status: 200,
headers,
});
}
return res ?? new Response(null, {
status: 404,
});
};
};
}
function bundleAssetUrl(path: string) {
return `${INTERNAL_PREFIX}${JS_PREFIX}/${BUILD_ID}${path}`;
}
/**
* Sort pages by their relative routing priority, based on the parts in the
* route matcher
*/
function sortRoutes<T extends { route: string }>(routes: T[]) {
routes.sort((a, b) => {
const partsA = a.route.split("/");
const partsB = b.route.split("/");
for (let i = 0; i < Math.max(partsA.length, partsB.length); i++) {
const partA = partsA[i];
const partB = partsB[i];
if (partA === undefined) return -1;
if (partB === undefined) return 1;
if (partA === partB) continue;
const priorityA = partA.startsWith(":") ? partA.endsWith("*") ? 0 : 1 : 2;
const priorityB = partB.startsWith(":") ? partB.endsWith("*") ? 0 : 1 : 2;
return Math.max(Math.min(priorityB - priorityA, 1), -1);
}
return 0;
});
}
/** Transform a filesystem URL path to a `path-to-regex` style matcher. */
function pathToRoute(path: string): string {
const parts = path.split("/");
if (parts[parts.length - 1] === "index") {
parts.pop();
}
const route = "/" + parts
.map((part) => {
if (part.startsWith("[...") && part.endsWith("]")) {
return `:${part.slice(4, part.length - 1)}*`;
}
if (part.startsWith("[") && part.endsWith("]")) {
return `:${part.slice(1, part.length - 1)}`;
}
return part;
})
.join("/");
return route;
}