From 572b8123c4414f05437bb4e2125a85b80e5897de Mon Sep 17 00:00:00 2001 From: Luca Casonato Date: Thu, 10 Jun 2021 20:46:10 +0200 Subject: [PATCH] refactor: centralize server into ServerContext (#26) This commit centralizes all server related logic into a central ServerContext class. --- makefile | 3 + src/server/bundle.ts | 2 +- src/server/context.ts | 181 ++++++++++++++++++++++++++++++++++++++++++ src/server/mod.ts | 23 ++---- src/server/render.ts | 34 ++++---- src/server/router.ts | 76 ------------------ src/server/routes.ts | 112 -------------------------- src/server/types.ts | 25 ++++++ tests/main_test.ts | 4 +- 9 files changed, 236 insertions(+), 224 deletions(-) create mode 100644 src/server/context.ts delete mode 100644 src/server/router.ts delete mode 100644 src/server/routes.ts create mode 100644 src/server/types.ts diff --git a/makefile b/makefile index 901b613f..815327f2 100644 --- a/makefile +++ b/makefile @@ -4,5 +4,8 @@ fmt: lint: deno lint +test: + deno test --no-check -A --config tsconfig.json + watch_example: deployctl run --watch --no-check example/main.ts \ No newline at end of file diff --git a/src/server/bundle.ts b/src/server/bundle.ts index 1ecda520..2bca9d85 100644 --- a/src/server/bundle.ts +++ b/src/server/bundle.ts @@ -1,5 +1,5 @@ import { denoPlugin, esbuild } from "./deps.ts"; -import { Page } from "./routes.ts"; +import { Page } from "./types.ts"; let esbuildInitalized: boolean | Promise = false; async function ensureEsbuildInialized() { diff --git a/src/server/context.ts b/src/server/context.ts new file mode 100644 index 00000000..5d359f4f --- /dev/null +++ b/src/server/context.ts @@ -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, + }; + 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(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; +} diff --git a/src/server/mod.ts b/src/server/mod.ts index f0f0c11f..34ccf266 100644 --- a/src/server/mod.ts +++ b/src/server/mod.ts @@ -1,31 +1,18 @@ +import { ServerContext } from "./context.ts"; import { router } from "./deps.ts"; -import { - ApiRoute, - ApiRouteModule, - Page, - PageModule, - processRoutes, -} from "./routes.ts"; -import { installRoutes } from "./router.ts"; +import { ApiRouteModule, PageModule } from "./types.ts"; export interface Routes { pages: Record; baseUrl: string; } -export { installRoutes, processRoutes, router }; +export { router, ServerContext }; export function start(routes: Routes) { - const [pages, apiRoutes] = processRoutes(routes); - const app = createDefaultRouter(pages, apiRoutes); + const ctx = ServerContext.fromRoutes(routes); + const app = router.router(ctx.routes()); addEventListener("fetch", (event: FetchEvent) => { event.respondWith(app(event.request)); }); } - -export function createDefaultRouter( - pages: Page[], - apiRoutes: ApiRoute[], -): router.RequestHandler { - return router.router(installRoutes(pages, apiRoutes)); -} diff --git a/src/server/render.ts b/src/server/render.ts index f2834e89..06d5c743 100644 --- a/src/server/render.ts +++ b/src/server/render.ts @@ -1,28 +1,32 @@ import { renderToString } from "./deps.ts"; import * as rt from "../runtime/deps.ts"; -import { Page } from "./routes.ts"; +import { Page } from "./types.ts"; -export function render( - page: Page, - imports: string[], - preloads: string[], - params: Record, -): string { - const props = { params }; +export interface RenderOptions { + page: Page; + imports: string[]; + preloads: string[]; + params: Record; +} + +export function render(options: RenderOptions): string { + const props = { params: options.params }; const propsStr = JSON.stringify(props); - const body = renderToString(rt.h(page.component, props)); + const body = renderToString(rt.h(options.page.component, props)); return ` ${ - preloads.map((src) => ``).join( - "\n ", - ) + options.preloads.map((src) => ``) + .join( + "\n ", + ) } ${ - imports.map((src) => ``).join( - "\n ", - ) + options.imports.map((src) => ``) + .join( + "\n ", + ) } diff --git a/src/server/router.ts b/src/server/router.ts deleted file mode 100644 index faf97a22..00000000 --- a/src/server/router.ts +++ /dev/null @@ -1,76 +0,0 @@ -import { mediaTypeLookup, router } from "./deps.ts"; -import { Bundler } from "./bundle.ts"; -import { render } from "./render.ts"; -import { ApiRoute, Page } from "./routes.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( - pages: Page[], - apiRoutes: ApiRoute[], -): router.Routes { - const bundler = new Bundler(pages); - - const routes: router.Routes = {}; - - for (const page of pages) { - const bundlePath = `/${page.name}.js`; - const imports = [bundleAssetUrl(bundlePath)]; - routes[page.route] = (_, match) => { - const preloads = bundler.getPreloads(bundlePath).map(bundleAssetUrl); - return new Response( - render(page, imports, preloads, match.params), - { - status: 200, - headers: { - "Content-Type": "text/html; charset=utf-8", - }, - }, - ); - }; - } - - for (const apiRoute of apiRoutes) { - routes[apiRoute.route] = apiRoute.handler; - } - - routes[`${INTERNAL_PREFIX}${JS_PREFIX}/${BUILD_ID}/:path*`] = - internalBundleAssetRoute(bundler); - - return routes; -} - -function bundleAssetUrl(path: string) { - return `${INTERNAL_PREFIX}${JS_PREFIX}/${BUILD_ID}${path}`; -} - -/** - * Returns a router that contains all fresh routes. Should be mounted at - * constants.INTERNAL_PREFIX - */ -function internalBundleAssetRoute(bundler: Bundler): router.MatchHandler { - return async (_req, match) => { - const path = `/${match.params.path}`; - const file = await 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, - }); - }; -} diff --git a/src/server/routes.ts b/src/server/routes.ts deleted file mode 100644 index 47a6b538..00000000 --- a/src/server/routes.ts +++ /dev/null @@ -1,112 +0,0 @@ -import { extname, router } from "./deps.ts"; -import * as rt from "../runtime/deps.ts"; -import { PageProps } from "../runtime/types.ts"; -import { Routes } from "./mod.ts"; - -export interface PageModule { - default: rt.ComponentType; -} - -export interface Page { - route: string; - url: string; - name: string; - component: rt.ComponentType; -} - -export interface ApiRouteModule { - default: router.MatchHandler; -} - -export interface ApiRoute { - route: string; - url: string; - name: string; - handler: router.MatchHandler; -} - -/** - * Process the routes into individual pages. - */ -export function processRoutes(routes: Routes): [Page[], ApiRoute[]] { - // 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 { - const page: Page = { - route, - url, - name, - component: module.default as rt.ComponentType, - }; - pages.push(page); - } - } - - sortRoutes(pages); - sortRoutes(apiRoutes); - - return [pages, apiRoutes]; -} - -/** - * Sort pages by their relative routing priority, based on the parts in the - * route matcher - */ -function sortRoutes(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; -} diff --git a/src/server/types.ts b/src/server/types.ts new file mode 100644 index 00000000..bc5bcae2 --- /dev/null +++ b/src/server/types.ts @@ -0,0 +1,25 @@ +import { ComponentType } from "../runtime/deps.ts"; +import { router } from "./deps.ts"; +import { PageProps } from "../runtime/types.ts"; + +export interface PageModule { + default: ComponentType; +} + +export interface Page { + route: string; + url: string; + name: string; + component: ComponentType; +} + +export interface ApiRouteModule { + default: router.MatchHandler; +} + +export interface ApiRoute { + route: string; + url: string; + name: string; + handler: router.MatchHandler; +} diff --git a/tests/main_test.ts b/tests/main_test.ts index c5e810d2..ff0c5dcc 100644 --- a/tests/main_test.ts +++ b/tests/main_test.ts @@ -1,8 +1,8 @@ -import { createDefaultRouter, processRoutes } from "../server.ts"; +import { router as r, ServerContext } from "../server.ts"; import { assert, assertEquals, assertStringIncludes } from "./deps.ts"; import routes from "./fixture/routes.gen.ts"; -const router = createDefaultRouter(...processRoutes(routes)); +const router = r.router(ServerContext.fromRoutes(routes).routes()); Deno.test("/ page prerender", async () => { const resp = await router(new Request("https://fresh.deno.dev/"));