feat: change to denosaurs router (#20)

This commit is contained in:
Leo K
2021-06-03 11:11:04 +02:00
committed by GitHub
parent a0bb5c05ee
commit a48da64dc3
6 changed files with 70 additions and 69 deletions
+5 -2
View File
@@ -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();
+8 -19
View File
@@ -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));
}
+41 -30
View File
@@ -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<Record<string, string>>(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,
});
};
}
+4 -4
View File
@@ -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<Record<string, string>>;
default: router.MatchHandler;
}
export interface ApiRoute {
route: string;
url: string;
name: string;
handler: oak.RouterMiddleware<Record<string, string>>;
handler: router.MatchHandler;
}
/**
@@ -49,7 +49,7 @@ export function processRoutes(routes: Routes): [Page[], ApiRoute[]] {
route,
url,
name,
handler: module.default as oak.RouterMiddleware<Record<string, string>>,
handler: module.default as router.MatchHandler,
};
apiRoutes.push(apiRoute);
} else {
+6 -4
View File
@@ -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",
},
});
};
+6 -10
View File
@@ -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);
});