From a48da64dc3aa050edbdc8c9e7112121758ae7415 Mon Sep 17 00:00:00 2001 From: Leo K Date: Thu, 3 Jun 2021 11:11:04 +0200 Subject: [PATCH] feat: change to denosaurs router (#20) --- src/server/deps.ts | 7 +++- src/server/mod.ts | 27 ++++--------- src/server/router.ts | 71 +++++++++++++++++++-------------- src/server/routes.ts | 8 ++-- tests/fixture/pages/api/name.ts | 10 +++-- tests/main_test.ts | 16 +++----- 6 files changed, 70 insertions(+), 69 deletions(-) diff --git a/src/server/deps.ts b/src/server/deps.ts index 7ef7db54..8d9f69af 100644 --- a/src/server/deps.ts +++ b/src/server/deps.ts @@ -5,8 +5,11 @@ export { renderToString } from "https://x.lcas.dev/preact@10.5.12/ssr.js"; export { extname } from "https://deno.land/std@0.95.0/path/mod.ts"; export { generate as generateUuid } from "https://deno.land/std@0.95.0/uuid/v4.ts"; -// -- oak -- -export * as oak from "https://deno.land/x/oak@v7.4.0/mod.ts"; +// -- router -- +export * as router from "https://crux.land/router@0.0.2"; + +// -- media types -- +export { lookup as mediaTypeLookup } from "https://deno.land/x/media_types@v2.8.4/mod.ts"; // -- esbuild -- const start = new Date().getTime(); diff --git a/src/server/mod.ts b/src/server/mod.ts index cc2b6d9d..f0f0c11f 100644 --- a/src/server/mod.ts +++ b/src/server/mod.ts @@ -1,4 +1,4 @@ -import { oak } from "./deps.ts"; +import { router } from "./deps.ts"; import { ApiRoute, ApiRouteModule, @@ -13,30 +13,19 @@ export interface Routes { baseUrl: string; } -export { installRoutes, oak, processRoutes }; +export { installRoutes, processRoutes, router }; export function start(routes: Routes) { const [pages, apiRoutes] = processRoutes(routes); - const app = createDefaultServer(pages, apiRoutes); - app.addEventListener("error", (err) => { - console.error(err.error); + const app = createDefaultRouter(pages, apiRoutes); + addEventListener("fetch", (event: FetchEvent) => { + event.respondWith(app(event.request)); }); - - addEventListener("fetch", app.fetchEventHandler()); } -export function createDefaultServer( +export function createDefaultRouter( pages: Page[], apiRoutes: ApiRoute[], -): oak.Application { - const router = new oak.Router(); - - installRoutes(router, pages, apiRoutes); - - const app = new oak.Application(); - - app.use(router.routes()); - app.use(router.allowedMethods()); - - return app; +): router.RequestHandler { + return router.router(installRoutes(pages, apiRoutes)); } diff --git a/src/server/router.ts b/src/server/router.ts index 822efcb2..5c5509cb 100644 --- a/src/server/router.ts +++ b/src/server/router.ts @@ -1,4 +1,4 @@ -import { extname, oak } from "./deps.ts"; +import { mediaTypeLookup, router } from "./deps.ts"; import { Bundler } from "./bundle.ts"; import { render } from "./render.ts"; import { ApiRoute, Page } from "./routes.ts"; @@ -6,34 +6,38 @@ 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[], 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)]; - router.get>(page.route, (ctx) => { - ctx.response.status = 200; - ctx.response.type = "html"; + routes[page.route] = (_, match) => { const preloads = bundler.getPreloads(bundlePath).map(bundleAssetUrl); - ctx.response.body = render(page, imports, preloads, ctx.params); - }); + return new Response( + render(page, imports, preloads, match.params), + { + status: 200, + headers: { + "Content-Type": "text/html; charset=utf-8", + }, + }, + ); + }; } for (const apiRoute of apiRoutes) { - router.all(apiRoute.route, apiRoute.handler); + routes[apiRoute.route] = apiRoute.handler; } - const internal = internalRouter(bundler); + routes[`/${INTERNAL_PREFIX}/${JS_PREFIX}/${BUILD_ID}/:path*`] = + internalBundleAssetRoute(bundler); - router.use( - INTERNAL_PREFIX, - internal.routes(), - internal.allowedMethods(), - ); + return routes; } function bundleAssetUrl(path: string) { @@ -44,22 +48,29 @@ function bundleAssetUrl(path: string) { * Returns a router that contains all fresh routes. Should be mounted at * constants.INTERNAL_PREFIX */ -function internalRouter(bundler: Bundler): oak.Router { - const router = new oak.Router(); - - router.get(`${JS_PREFIX}/${BUILD_ID}/:path*`, async (ctx) => { - const path = `/${ctx.params.path}`; +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) { - ctx.response.status = 200; - ctx.response.type = extname(path); - ctx.response.body = file; - ctx.response.headers.set( - "Cache-Control", - "public, max-age=604800, immutable", - ); - } - }); + const headers = new Headers({ + "Cache-Control": "public, max-age=604800, immutable", + }); - return router; + 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 index 816c4969..47a6b538 100644 --- a/src/server/routes.ts +++ b/src/server/routes.ts @@ -1,4 +1,4 @@ -import { extname, oak } from "./deps.ts"; +import { extname, router } from "./deps.ts"; import * as rt from "../runtime/deps.ts"; import { PageProps } from "../runtime/types.ts"; import { Routes } from "./mod.ts"; @@ -15,14 +15,14 @@ export interface Page { } export interface ApiRouteModule { - default: oak.RouterMiddleware>; + default: router.MatchHandler; } export interface ApiRoute { route: string; url: string; name: string; - handler: oak.RouterMiddleware>; + handler: router.MatchHandler; } /** @@ -49,7 +49,7 @@ export function processRoutes(routes: Routes): [Page[], ApiRoute[]] { route, url, name, - handler: module.default as oak.RouterMiddleware>, + handler: module.default as router.MatchHandler, }; apiRoutes.push(apiRoute); } else { diff --git a/tests/fixture/pages/api/name.ts b/tests/fixture/pages/api/name.ts index 7f70b590..9e54e7a7 100644 --- a/tests/fixture/pages/api/name.ts +++ b/tests/fixture/pages/api/name.ts @@ -1,5 +1,7 @@ -import { oak } from "../../api_deps.ts"; - -export default (ctx: oak.Context) => { - ctx.response.body = { name: "fresh" }; +export default () => { + return new Response(JSON.stringify({ name: "fresh" }), { + headers: { + "Content-Type": "application/json; charset=utf-8", + }, + }); }; diff --git a/tests/main_test.ts b/tests/main_test.ts index fc2df8b7..c5e810d2 100644 --- a/tests/main_test.ts +++ b/tests/main_test.ts @@ -1,15 +1,11 @@ -import { installRoutes, oak, processRoutes } from "../server.ts"; +import { createDefaultRouter, processRoutes } from "../server.ts"; import { assert, assertEquals, assertStringIncludes } from "./deps.ts"; import routes from "./fixture/routes.gen.ts"; -const router = new oak.Router(); -installRoutes(router, ...processRoutes(routes)); -const app = new oak.Application(); -app.use(router.routes()); -app.use(router.allowedMethods()); +const router = createDefaultRouter(...processRoutes(routes)); Deno.test("/ page prerender", async () => { - const resp = await app.handle(new Request("https://fresh.deno.dev/")); + const resp = await router(new Request("https://fresh.deno.dev/")); assert(resp); assertEquals(resp.status, 200); assertEquals(resp.headers.get("content-type"), "text/html; charset=utf-8"); @@ -23,7 +19,7 @@ Deno.test("/ page prerender", async () => { }); Deno.test("/[name] page prerender", async () => { - const resp = await app.handle(new Request("https://fresh.deno.dev/foo")); + const resp = await router(new Request("https://fresh.deno.dev/foo")); assert(resp); assertEquals(resp.status, 200); assertEquals(resp.headers.get("content-type"), "text/html; charset=utf-8"); @@ -37,7 +33,7 @@ Deno.test("/[name] page prerender", async () => { }); Deno.test("/api/name", async () => { - const resp = await app.handle(new Request("https://fresh.deno.dev/api/name")); + const resp = await router(new Request("https://fresh.deno.dev/api/name")); assert(resp); assertEquals(resp.status, 200); assertEquals( @@ -49,7 +45,7 @@ Deno.test("/api/name", async () => { }); Deno.test("/api/xyz not found", async () => { - const resp = await app.handle(new Request("https://fresh.deno.dev/api/xyz")); + const resp = await router(new Request("https://fresh.deno.dev/api/xyz")); assert(resp); assertEquals(resp.status, 404); });