BREAKING: merge API routes and pages concept (#53)

This commit merges API routes and pages into a single concept. The
pages/api folder is now not special anymore.
This commit is contained in:
Luca Casonato
2021-09-25 10:49:53 +02:00
committed by GitHub
parent aeaddb1eaa
commit f5b3faf0d8
12 changed files with 150 additions and 121 deletions
+2 -3
View File
@@ -13,9 +13,8 @@ done automatically when you run the `fresh routes` command. You never have to
edit this file manually. edit this file manually.
The files in the `pages` subfolder describe the HTML pages and API endpoints of The files in the `pages` subfolder describe the HTML pages and API endpoints of
your application. Files inside the `pages/api` subdirectory are treated as API your application. All pages can act as both API endpoints and possibly dynamic
routes, while all other files are treated as possibly dynamic HTML pages. More HTML pages. More info about how the `pages` subfolder works can be found on the
info about how the `pages` subfolder works can be found on the
[file system routing](./file-system-routing.md) page. [file system routing](./file-system-routing.md) page.
Finally there is a `deps.ts` and `api_deps.ts`. These files are the central Finally there is a `deps.ts` and `api_deps.ts`. These files are the central
+3 -1
View File
@@ -1,3 +1,5 @@
import { HandlerContext } from "../../../server.ts";
// Jokes courtesy of https://punsandoneliners.com/randomness/programmer-jokes/ // Jokes courtesy of https://punsandoneliners.com/randomness/programmer-jokes/
const JOKES = [ const JOKES = [
"Why do Java developers often wear glasses? They can’t C#.", "Why do Java developers often wear glasses? They can’t C#.",
@@ -12,7 +14,7 @@ const JOKES = [
"An SEO expert walked into a bar, pub, inn, tavern, hostelry, public house.", "An SEO expert walked into a bar, pub, inn, tavern, hostelry, public house.",
]; ];
export default (_req: Request): Response => { export const handler = (_ctx: HandlerContext): Response => {
const randomIndex = Math.floor(Math.random() * 10); const randomIndex = Math.floor(Math.random() * 10);
const body = JOKES[randomIndex]; const body = JOKES[randomIndex];
return new Response(body); return new Response(body);
+3 -1
View File
@@ -32,7 +32,9 @@ export class Bundler {
const entryPoints: Record<string, string> = {}; const entryPoints: Record<string, string> = {};
for (const page of this.#pages) { for (const page of this.#pages) {
entryPoints[page.name] = `fresh:///${page.name}`; if (page.component !== undefined && page.runtimeJS) {
entryPoints[page.name] = `fresh:///${page.name}`;
}
} }
await ensureEsbuildInialized(); await ensureEsbuildInialized();
+52 -53
View File
@@ -5,24 +5,21 @@ import { INTERNAL_PREFIX } from "./constants.ts";
import { JS_PREFIX } from "./constants.ts"; import { JS_PREFIX } from "./constants.ts";
import { BUILD_ID } from "./constants.ts"; import { BUILD_ID } from "./constants.ts";
import { import {
ApiRoute, Handler,
ApiRouteModule,
Page, Page,
PageModule, PageModule,
Renderer, Renderer,
RendererModule, RendererModule,
} from "./types.ts"; } from "./types.ts";
import { render } from "./render.tsx"; import { render as internalRender } from "./render.tsx";
export class ServerContext { export class ServerContext {
#pages: Page[]; #pages: Page[];
#apiRoutes: ApiRoute[];
#bundler: Bundler; #bundler: Bundler;
#renderer: Renderer; #renderer: Renderer;
constructor(pages: Page[], apiRoutes: ApiRoute[], renderer: Renderer) { constructor(pages: Page[], renderer: Renderer) {
this.#pages = pages; this.#pages = pages;
this.#apiRoutes = apiRoutes;
this.#renderer = renderer; this.#renderer = renderer;
this.#bundler = new Bundler(pages); this.#bundler = new Bundler(pages);
} }
@@ -34,9 +31,8 @@ export class ServerContext {
// Get the routes' base URL. // Get the routes' base URL.
const baseUrl = new URL("./", routes.baseUrl).href; const baseUrl = new URL("./", routes.baseUrl).href;
// Extract all pages, and prepare them into this `Page` structure. // Extract all routes, and prepare them into the `Page` structure.
const pages: Page[] = []; const pages: Page[] = [];
const apiRoutes: ApiRoute[] = [];
let renderer: Renderer = DEFAULT_RENDERER; let renderer: Renderer = DEFAULT_RENDERER;
for (const [self, module] of Object.entries(routes.pages)) { for (const [self, module] of Object.entries(routes.pages)) {
const url = new URL(self, baseUrl).href; const url = new URL(self, baseUrl).href;
@@ -47,27 +43,22 @@ export class ServerContext {
const baseRoute = path.substring(1, path.length - extname(path).length); const baseRoute = path.substring(1, path.length - extname(path).length);
const route = pathToRoute(baseRoute); const route = pathToRoute(baseRoute);
const name = baseRoute.replace("/", "-"); const name = baseRoute.replace("/", "-");
if (path.startsWith("/api/")) { if (!path.startsWith("/_")) {
const handlers = Object.fromEntries(
Object.entries(module as ApiRouteModule).filter(([method]) =>
method === "default" ||
(router.METHODS as readonly string[]).includes(method)
),
);
const apiRoute: ApiRoute = {
route,
url,
name,
handlers,
};
apiRoutes.push(apiRoute);
} else if (!path.startsWith("/_")) {
const { default: component, config } = (module as PageModule); const { default: component, config } = (module as PageModule);
let { handler } = (module as PageModule);
handler ??= {};
if (
component &&
typeof handler === "object" && handler.GET === undefined
) {
handler.GET = ({ render }) => render!();
}
const page: Page = { const page: Page = {
route, route,
url, url,
name, name,
component, component,
handler,
runtimeJS: config?.runtimeJS ?? true, runtimeJS: config?.runtimeJS ?? true,
}; };
pages.push(page); pages.push(page);
@@ -79,9 +70,8 @@ export class ServerContext {
} }
} }
sortRoutes(pages); sortRoutes(pages);
sortRoutes(apiRoutes);
return new ServerContext(pages, apiRoutes, renderer); return new ServerContext(pages, renderer);
} }
/** /**
@@ -93,36 +83,45 @@ export class ServerContext {
for (const page of this.#pages) { for (const page of this.#pages) {
const bundlePath = `/${page.name}.js`; const bundlePath = `/${page.name}.js`;
const imports = [bundleAssetUrl(bundlePath)]; const imports = page.runtimeJS ? [bundleAssetUrl(bundlePath)] : [];
routes[page.route] = async (req, match) => { const createRender = (
const preloads = this.#bundler.getPreloads(bundlePath).map( req: Request,
bundleAssetUrl, params: Record<string, string | string[]>,
); ) => {
const body = await render({ if (page.component === undefined) return undefined;
page, const render = async () => {
imports: page.runtimeJS ? imports : [], const preloads = page.runtimeJS
preloads: page.runtimeJS ? preloads : [], ? this.#bundler.getPreloads(bundlePath).map(bundleAssetUrl)
renderer: this.#renderer, : [];
url: new URL(req.url), const body = await internalRender({
params: match.params, page,
}); imports,
return new Response(body, { preloads,
status: 200, renderer: this.#renderer,
headers: { url: new URL(req.url),
"content-type": "text/html; charset=utf-8", params,
}, });
}); return new Response(body, {
status: 200,
headers: {
"content-type": "text/html; charset=utf-8",
},
});
};
return render;
}; };
}
for (const { route, handlers } of this.#apiRoutes) { if (typeof page.handler === "function") {
for (const [method, handler] of Object.entries(handlers)) { routes[page.route] = (req, match) =>
if (handler) { (page.handler as Handler)({
if (method === "default") { req,
routes[route] = handler; match,
} else { render: createRender(req, match.params),
routes[`${method}@${route}`] = handler; });
} } else {
for (const [method, handler] of Object.entries(page.handler)) {
routes[`${method}@${page.route}`] = (req, match) =>
handler({ req, match, render: createRender(req, match.params) });
} }
} }
} }
+3 -2
View File
@@ -1,11 +1,12 @@
import { ServerContext } from "./context.ts"; import { ServerContext } from "./context.ts";
import { router } from "./deps.ts"; import { router } from "./deps.ts";
import { ApiRouteModule, PageModule, RendererModule } from "./types.ts"; import { PageModule, RendererModule } from "./types.ts";
export type { Handler, HandlerContext, Handlers } from "./types.ts";
export { RenderContext } from "./render.tsx"; export { RenderContext } from "./render.tsx";
export type { RenderFn } from "./render.tsx"; export type { RenderFn } from "./render.tsx";
export interface Routes { export interface Routes {
pages: Record<string, PageModule | ApiRouteModule | RendererModule>; pages: Record<string, PageModule | RendererModule>;
baseUrl: string; baseUrl: string;
} }
+1 -1
View File
@@ -81,7 +81,7 @@ export async function render(opts: RenderOptions): Promise<string> {
const vnode = h(DATA_CONTEXT.Provider, { const vnode = h(DATA_CONTEXT.Provider, {
value: dataCache, value: dataCache,
children: h(opts.page.component, props), children: h(opts.page.component!, props),
}); });
const ctx = new RenderContext(crypto.randomUUID(), opts.url, opts.page.route); const ctx = new RenderContext(crypto.randomUUID(), opts.url, opts.page.route);
+18 -13
View File
@@ -4,29 +4,34 @@ import { PageConfig, PageProps } from "../runtime/types.ts";
import { RenderContext, RenderFn } from "./render.tsx"; import { RenderContext, RenderFn } from "./render.tsx";
export interface PageModule { export interface PageModule {
default: ComponentType<PageProps>; default?: ComponentType<PageProps>;
handler?: Handler | Handlers;
config?: PageConfig; config?: PageConfig;
} }
export interface HandlerContext<
T extends Record<string, string> = Record<string, string>,
> {
req: Request;
match: router.MatchResult<T>;
render?: () => Promise<Response>;
}
export type Handler = (ctx: HandlerContext) => Response | Promise<Response>;
export type Handlers = {
[K in typeof router.METHODS[number]]?: Handler;
};
export interface Page { export interface Page {
route: string; route: string;
url: string; url: string;
name: string; name: string;
component: ComponentType<PageProps>; component?: ComponentType<PageProps>;
handler: Handler | Handlers;
runtimeJS: boolean; runtimeJS: boolean;
} }
export type ApiRouteModule = {
[K in "default" | typeof router.METHODS[number]]?: router.MatchHandler;
};
export interface ApiRoute {
route: string;
url: string;
name: string;
handlers: Record<string, router.MatchHandler>;
}
export interface RendererModule { export interface RendererModule {
render(ctx: RenderContext, render: RenderFn): void; render(ctx: RenderContext, render: RenderFn): void;
postRender(ctx: RenderContext, bodyHtml: string): void; postRender(ctx: RenderContext, bodyHtml: string): void;
+12 -11
View File
@@ -1,11 +1,12 @@
export function GET() { export const handler = {
return new Response("Get fresh!", { GET() {
headers: { return new Response("Get fresh!", {
"Content-Type": "application/json; charset=utf-8", headers: {
}, "Content-Type": "application/json; charset=utf-8",
}); },
} });
},
export function NOTAMETHOD() { NOTAMETHOD() {
return new Response("unreachable"); throw new Error("unreachable");
} },
};
-15
View File
@@ -1,15 +0,0 @@
export default () => {
return new Response(JSON.stringify({ name: "fresh" }), {
headers: {
"Content-Type": "application/json; charset=utf-8",
},
});
};
export function GET() {
return new Response("Get fresh!", {
headers: {
"Content-Type": "application/json; charset=utf-8",
},
});
}
+21
View File
@@ -0,0 +1,21 @@
/** @jsx h */
import { h } from "../deps.ts";
import { HandlerContext } from "../../../server.ts";
export default function Page() {
return <div>This is HTML</div>;
}
export const handler = {
GET({ req, render }: HandlerContext) {
if (req.headers.get("accept")?.includes("text/html")) {
return render!();
} else {
return new Response("This is plain text");
}
},
POST() {
return new Response("POST response");
},
};
+2 -2
View File
@@ -6,7 +6,7 @@ import * as $0 from "./pages/index.tsx";
import * as $1 from "./pages/static.tsx"; import * as $1 from "./pages/static.tsx";
import * as $2 from "./pages/props/[id].tsx"; import * as $2 from "./pages/props/[id].tsx";
import * as $3 from "./pages/api/get_only.ts"; import * as $3 from "./pages/api/get_only.ts";
import * as $4 from "./pages/api/name.ts"; import * as $4 from "./pages/intercept.tsx";
import * as $5 from "./pages/[name].tsx"; import * as $5 from "./pages/[name].tsx";
const routes = { const routes = {
@@ -15,7 +15,7 @@ const routes = {
"./pages/static.tsx": $1, "./pages/static.tsx": $1,
"./pages/props/[id].tsx": $2, "./pages/props/[id].tsx": $2,
"./pages/api/get_only.ts": $3, "./pages/api/get_only.ts": $3,
"./pages/api/name.ts": $4, "./pages/intercept.tsx": $4,
"./pages/[name].tsx": $5, "./pages/[name].tsx": $5,
}, },
baseUrl: import.meta.url, baseUrl: import.meta.url,
+33 -19
View File
@@ -54,28 +54,46 @@ Deno.test("/[name] page prerender", async () => {
); );
}); });
Deno.test("/api/name - GET", async () => { Deno.test("/intercept - GET html", async () => {
const resp = await router(new Request("https://fresh.deno.dev/api/name")); const req = new Request("https://fresh.deno.dev/intercept", {
headers: { "accept": "text/html" },
});
const resp = await router(req);
assert(resp); assert(resp);
assertEquals(resp.status, 200); assertEquals(resp.status, 200);
const body = await resp.text(); const body = await resp.text();
assertEquals(body, "Get fresh!"); assert(body.includes("<div>This is HTML</div>"));
}); });
Deno.test("/api/name - default", async () => { Deno.test("/intercept - GET text", async () => {
const resp = await router( const req = new Request("https://fresh.deno.dev/intercept", {
new Request("https://fresh.deno.dev/api/name", { headers: { "accept": "text/plain" },
method: "POST", });
}), const resp = await router(req);
);
assert(resp); assert(resp);
assertEquals(resp.status, 200); assertEquals(resp.status, 200);
assertEquals( const body = await resp.text();
resp.headers.get("content-type"), assertEquals(body, "This is plain text");
"application/json; charset=utf-8", });
);
const body = await resp.json(); Deno.test("/intercept - POST", async () => {
assertEquals(body, { name: "fresh" }); const req = new Request("https://fresh.deno.dev/intercept", {
method: "POST",
});
const resp = await router(req);
assert(resp);
assertEquals(resp.status, 200);
const body = await resp.text();
assertEquals(body, "POST response");
});
Deno.test("/intercept - DELETE", async () => {
const req = new Request("https://fresh.deno.dev/intercept", {
method: "DELETE",
});
const resp = await router(req);
assert(resp);
assertEquals(resp.status, 405);
}); });
Deno.test("/api/get_only - NOTAMETHOD", async () => { Deno.test("/api/get_only - NOTAMETHOD", async () => {
@@ -86,10 +104,6 @@ Deno.test("/api/get_only - NOTAMETHOD", async () => {
); );
assert(resp); assert(resp);
assertEquals(resp.status, 405); assertEquals(resp.status, 405);
assertEquals(
resp.headers.get("accept"),
"GET",
);
}); });
Deno.test("/api/xyz not found", async () => { Deno.test("/api/xyz not found", async () => {