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.
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
routes, while all other files are treated as possibly dynamic HTML pages. More
info about how the `pages` subfolder works can be found on the
your application. All pages can act as both API endpoints and possibly dynamic
HTML pages. More info about how the `pages` subfolder works can be found on the
[file system routing](./file-system-routing.md) page.
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/
const JOKES = [
"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.",
];
export default (_req: Request): Response => {
export const handler = (_ctx: HandlerContext): Response => {
const randomIndex = Math.floor(Math.random() * 10);
const body = JOKES[randomIndex];
return new Response(body);
+3 -1
View File
@@ -32,7 +32,9 @@ export class Bundler {
const entryPoints: Record<string, string> = {};
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();
+52 -53
View File
@@ -5,24 +5,21 @@ import { INTERNAL_PREFIX } from "./constants.ts";
import { JS_PREFIX } from "./constants.ts";
import { BUILD_ID } from "./constants.ts";
import {
ApiRoute,
ApiRouteModule,
Handler,
Page,
PageModule,
Renderer,
RendererModule,
} from "./types.ts";
import { render } from "./render.tsx";
import { render as internalRender } from "./render.tsx";
export class ServerContext {
#pages: Page[];
#apiRoutes: ApiRoute[];
#bundler: Bundler;
#renderer: Renderer;
constructor(pages: Page[], apiRoutes: ApiRoute[], renderer: Renderer) {
constructor(pages: Page[], renderer: Renderer) {
this.#pages = pages;
this.#apiRoutes = apiRoutes;
this.#renderer = renderer;
this.#bundler = new Bundler(pages);
}
@@ -34,9 +31,8 @@ export class ServerContext {
// Get the routes' base URL.
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 apiRoutes: ApiRoute[] = [];
let renderer: Renderer = DEFAULT_RENDERER;
for (const [self, module] of Object.entries(routes.pages)) {
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 route = pathToRoute(baseRoute);
const name = baseRoute.replace("/", "-");
if (path.startsWith("/api/")) {
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("/_")) {
if (!path.startsWith("/_")) {
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 = {
route,
url,
name,
component,
handler,
runtimeJS: config?.runtimeJS ?? true,
};
pages.push(page);
@@ -79,9 +70,8 @@ export class ServerContext {
}
}
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) {
const bundlePath = `/${page.name}.js`;
const imports = [bundleAssetUrl(bundlePath)];
routes[page.route] = async (req, match) => {
const preloads = this.#bundler.getPreloads(bundlePath).map(
bundleAssetUrl,
);
const body = await render({
page,
imports: page.runtimeJS ? imports : [],
preloads: page.runtimeJS ? preloads : [],
renderer: this.#renderer,
url: new URL(req.url),
params: match.params,
});
return new Response(body, {
status: 200,
headers: {
"content-type": "text/html; charset=utf-8",
},
});
const imports = page.runtimeJS ? [bundleAssetUrl(bundlePath)] : [];
const createRender = (
req: Request,
params: Record<string, string | string[]>,
) => {
if (page.component === undefined) return undefined;
const render = async () => {
const preloads = page.runtimeJS
? this.#bundler.getPreloads(bundlePath).map(bundleAssetUrl)
: [];
const body = await internalRender({
page,
imports,
preloads,
renderer: this.#renderer,
url: new URL(req.url),
params,
});
return new Response(body, {
status: 200,
headers: {
"content-type": "text/html; charset=utf-8",
},
});
};
return render;
};
}
for (const { route, handlers } of this.#apiRoutes) {
for (const [method, handler] of Object.entries(handlers)) {
if (handler) {
if (method === "default") {
routes[route] = handler;
} else {
routes[`${method}@${route}`] = handler;
}
if (typeof page.handler === "function") {
routes[page.route] = (req, match) =>
(page.handler as Handler)({
req,
match,
render: createRender(req, match.params),
});
} 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 { 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 type { RenderFn } from "./render.tsx";
export interface Routes {
pages: Record<string, PageModule | ApiRouteModule | RendererModule>;
pages: Record<string, PageModule | RendererModule>;
baseUrl: string;
}
+1 -1
View File
@@ -81,7 +81,7 @@ export async function render(opts: RenderOptions): Promise<string> {
const vnode = h(DATA_CONTEXT.Provider, {
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);
+18 -13
View File
@@ -4,29 +4,34 @@ import { PageConfig, PageProps } from "../runtime/types.ts";
import { RenderContext, RenderFn } from "./render.tsx";
export interface PageModule {
default: ComponentType<PageProps>;
default?: ComponentType<PageProps>;
handler?: Handler | Handlers;
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 {
route: string;
url: string;
name: string;
component: ComponentType<PageProps>;
component?: ComponentType<PageProps>;
handler: Handler | Handlers;
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 {
render(ctx: RenderContext, render: RenderFn): void;
postRender(ctx: RenderContext, bodyHtml: string): void;
+12 -11
View File
@@ -1,11 +1,12 @@
export function GET() {
return new Response("Get fresh!", {
headers: {
"Content-Type": "application/json; charset=utf-8",
},
});
}
export function NOTAMETHOD() {
return new Response("unreachable");
}
export const handler = {
GET() {
return new Response("Get fresh!", {
headers: {
"Content-Type": "application/json; charset=utf-8",
},
});
},
NOTAMETHOD() {
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 $2 from "./pages/props/[id].tsx";
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";
const routes = {
@@ -15,7 +15,7 @@ const routes = {
"./pages/static.tsx": $1,
"./pages/props/[id].tsx": $2,
"./pages/api/get_only.ts": $3,
"./pages/api/name.ts": $4,
"./pages/intercept.tsx": $4,
"./pages/[name].tsx": $5,
},
baseUrl: import.meta.url,
+33 -19
View File
@@ -54,28 +54,46 @@ Deno.test("/[name] page prerender", async () => {
);
});
Deno.test("/api/name - GET", async () => {
const resp = await router(new Request("https://fresh.deno.dev/api/name"));
Deno.test("/intercept - GET html", async () => {
const req = new Request("https://fresh.deno.dev/intercept", {
headers: { "accept": "text/html" },
});
const resp = await router(req);
assert(resp);
assertEquals(resp.status, 200);
const body = await resp.text();
assertEquals(body, "Get fresh!");
assert(body.includes("<div>This is HTML</div>"));
});
Deno.test("/api/name - default", async () => {
const resp = await router(
new Request("https://fresh.deno.dev/api/name", {
method: "POST",
}),
);
Deno.test("/intercept - GET text", async () => {
const req = new Request("https://fresh.deno.dev/intercept", {
headers: { "accept": "text/plain" },
});
const resp = await router(req);
assert(resp);
assertEquals(resp.status, 200);
assertEquals(
resp.headers.get("content-type"),
"application/json; charset=utf-8",
);
const body = await resp.json();
assertEquals(body, { name: "fresh" });
const body = await resp.text();
assertEquals(body, "This is plain text");
});
Deno.test("/intercept - POST", async () => {
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 () => {
@@ -86,10 +104,6 @@ Deno.test("/api/get_only - NOTAMETHOD", async () => {
);
assert(resp);
assertEquals(resp.status, 405);
assertEquals(
resp.headers.get("accept"),
"GET",
);
});
Deno.test("/api/xyz not found", async () => {