From f5b3faf0d85cb2ec673dbd8b9cc4ed1e2d959e25 Mon Sep 17 00:00:00 2001 From: Luca Casonato Date: Sat, 25 Sep 2021 10:49:53 +0200 Subject: [PATCH] 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. --- docs/project-structure.md | 5 +- example/pages/api/joke.ts | 4 +- src/server/bundle.ts | 4 +- src/server/context.ts | 105 ++++++++++++++-------------- src/server/mod.ts | 5 +- src/server/render.tsx | 2 +- src/server/types.ts | 31 ++++---- tests/fixture/pages/api/get_only.ts | 23 +++--- tests/fixture/pages/api/name.ts | 15 ---- tests/fixture/pages/intercept.tsx | 21 ++++++ tests/fixture/routes.gen.ts | 4 +- tests/main_test.ts | 52 +++++++++----- 12 files changed, 150 insertions(+), 121 deletions(-) delete mode 100644 tests/fixture/pages/api/name.ts create mode 100644 tests/fixture/pages/intercept.tsx diff --git a/docs/project-structure.md b/docs/project-structure.md index eac56e12..7d40e8ff 100644 --- a/docs/project-structure.md +++ b/docs/project-structure.md @@ -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 diff --git a/example/pages/api/joke.ts b/example/pages/api/joke.ts index 33e02bd2..86656fa5 100644 --- a/example/pages/api/joke.ts +++ b/example/pages/api/joke.ts @@ -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); diff --git a/src/server/bundle.ts b/src/server/bundle.ts index e567d563..645aad25 100644 --- a/src/server/bundle.ts +++ b/src/server/bundle.ts @@ -32,7 +32,9 @@ export class Bundler { const entryPoints: Record = {}; 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(); diff --git a/src/server/context.ts b/src/server/context.ts index 0fef084b..5b34c9c2 100644 --- a/src/server/context.ts +++ b/src/server/context.ts @@ -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, + ) => { + 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) }); } } } diff --git a/src/server/mod.ts b/src/server/mod.ts index 3992225c..d7994fc2 100644 --- a/src/server/mod.ts +++ b/src/server/mod.ts @@ -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; + pages: Record; baseUrl: string; } diff --git a/src/server/render.tsx b/src/server/render.tsx index 4d4a3caf..d7e2c061 100644 --- a/src/server/render.tsx +++ b/src/server/render.tsx @@ -81,7 +81,7 @@ export async function render(opts: RenderOptions): Promise { 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); diff --git a/src/server/types.ts b/src/server/types.ts index d4b56956..11447398 100644 --- a/src/server/types.ts +++ b/src/server/types.ts @@ -4,29 +4,34 @@ import { PageConfig, PageProps } from "../runtime/types.ts"; import { RenderContext, RenderFn } from "./render.tsx"; export interface PageModule { - default: ComponentType; + default?: ComponentType; + handler?: Handler | Handlers; config?: PageConfig; } +export interface HandlerContext< + T extends Record = Record, +> { + req: Request; + match: router.MatchResult; + render?: () => Promise; +} + +export type Handler = (ctx: HandlerContext) => Response | Promise; + +export type Handlers = { + [K in typeof router.METHODS[number]]?: Handler; +}; + export interface Page { route: string; url: string; name: string; - component: ComponentType; + component?: ComponentType; + 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; -} - export interface RendererModule { render(ctx: RenderContext, render: RenderFn): void; postRender(ctx: RenderContext, bodyHtml: string): void; diff --git a/tests/fixture/pages/api/get_only.ts b/tests/fixture/pages/api/get_only.ts index 1f3582f1..6e541156 100644 --- a/tests/fixture/pages/api/get_only.ts +++ b/tests/fixture/pages/api/get_only.ts @@ -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"); + }, +}; diff --git a/tests/fixture/pages/api/name.ts b/tests/fixture/pages/api/name.ts deleted file mode 100644 index bee2a3d6..00000000 --- a/tests/fixture/pages/api/name.ts +++ /dev/null @@ -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", - }, - }); -} diff --git a/tests/fixture/pages/intercept.tsx b/tests/fixture/pages/intercept.tsx new file mode 100644 index 00000000..0f287b47 --- /dev/null +++ b/tests/fixture/pages/intercept.tsx @@ -0,0 +1,21 @@ +/** @jsx h */ + +import { h } from "../deps.ts"; +import { HandlerContext } from "../../../server.ts"; + +export default function Page() { + return
This is HTML
; +} + +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"); + }, +}; diff --git a/tests/fixture/routes.gen.ts b/tests/fixture/routes.gen.ts index 44743295..e2f4fdf8 100644 --- a/tests/fixture/routes.gen.ts +++ b/tests/fixture/routes.gen.ts @@ -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, diff --git a/tests/main_test.ts b/tests/main_test.ts index 0c5109b2..b291cb6d 100644 --- a/tests/main_test.ts +++ b/tests/main_test.ts @@ -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("
This is HTML
")); }); -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 () => {