From f2162d24bf9fc1adfc7ac1729284ac429426a914 Mon Sep 17 00:00:00 2001 From: Luca Casonato Date: Fri, 24 May 2024 18:31:34 +0200 Subject: [PATCH] feat: add `render` function (#2454) --- src/define.ts | 29 +++++++++---- src/handlers.ts | 49 ++++++++++++++++++++-- src/mod.ts | 3 +- src/plugins/fs_routes/mod_test.tsx | 4 +- src/plugins/fs_routes/render_middleware.ts | 4 +- www/routes/_app.tsx | 4 +- www/routes/docs/[...slug].tsx | 41 +++++++++--------- www/routes/index.tsx | 12 +++--- www/routes/raw.ts | 7 ++-- www/routes/recipes/_middleware.ts | 4 +- www/routes/showcase.tsx | 11 ++--- www/routes/thanks.tsx | 11 ++--- www/routes/update.tsx | 6 +-- www/utils/state.ts | 2 +- 14 files changed, 123 insertions(+), 64 deletions(-) diff --git a/src/define.ts b/src/define.ts index daba44fe..16402bc5 100644 --- a/src/define.ts +++ b/src/define.ts @@ -18,6 +18,8 @@ export interface Define { * of your route handlers. For example: * * ```ts + * import { define } from "../utils.ts"; + * * export const handler = define.handlers((ctx) => { * ctx.url; // ctx is inferred to be a FreshContext object, so this is a URL * return new Response("Hello, world!"); @@ -29,19 +31,22 @@ export interface Define { * For more information, see {@link Define.page}. * * You can also pass an explicit type argument to ensure that all data - * returned from the render function is of the correct type: + * returned from the handler is of the correct type: * * ```ts + * import { page } from "@fresh/core"; + * import { define } from "../utils.ts"; + * * export const handler = define.handlers<{ slug: string }>({ * async GET(ctx) { * const slug = ctx.params.slug; // slug is inferred to be a string - * return { data: { slug } }; + * return page({ slug }); * }, * * // This method will cause a type error because the data object is missing * // the required `slug` property. * async POST(ctx) { - * return { data: { } }; + * return page({ }); * }, * }); * ``` @@ -64,6 +69,8 @@ export interface Define { * of the data that your page component receives. For example: * * ```ts + * import { define } from "../utils.ts"; + * * export default define.page((props) => { * const slug = props.params.slug; // Because props is inferred to be a FreshContext object, slug is inferred to be a string * return

{slug}

; @@ -75,10 +82,13 @@ export interface Define { * return type of the handler method. * * ```ts + * import { page } from "@fresh/core"; + * import { define } from "../utils.ts"; + * * export const handler = define.handlers({ * async GET(ctx) { * const slug = ctx.params.slug; // slug is inferred to be a string - * return { data: { slug } }; + * return page({ slug }); * }, * }); * @@ -97,7 +107,8 @@ export interface Define { * @typeParam Data The type of data that the page component receives. This will be inferred from the handler methods if not provided. In very advanced use cases, you can specify `never` to the `Handler` type argument and provide the `Data` type explicitly. */ page< - Handler extends RouteHandler = never, + // deno-lint-ignore no-explicit-any + Handler extends RouteHandler = never, Data = Handler extends HandlerByMethod ? Data : never, >( render: AnyComponent & { Component: () => null }>, @@ -112,6 +123,8 @@ export interface Define { * of the context object that your middleware receives. For example: * * ```ts + * import { define } from "../utils.ts"; + * * export const middleware = define.middleware((ctx) => { * ctx.url; // ctx is inferred to be a FreshContext object, so this is a URL * return ctx.next(); @@ -122,7 +135,7 @@ export interface Define { * * @typeParam M The type of the middleware function. This will be inferred from the input function. Do not manually specify this type. */ - defineMiddleware>( + middleware>( middleware: M, ): typeof middleware; } @@ -136,7 +149,7 @@ export interface Define { * it to define your routes and middleware using the * {@link Define.handlers|define.handlers}, * {@link Define.page|define.page}, and - * {@link Define.defineMiddleware|define.middleware} functions. + * {@link Define.middleware|define.middleware} functions. * * @typeParam State The type of the state object that is passed to all middleware and route handlers. */ @@ -148,7 +161,7 @@ export function createDefine(): Define { page(render) { return render; }, - defineMiddleware(middleware) { + middleware(middleware) { return middleware; }, }; diff --git a/src/handlers.ts b/src/handlers.ts index f94c391a..b9f59d0b 100644 --- a/src/handlers.ts +++ b/src/handlers.ts @@ -1,10 +1,52 @@ import type { FreshContext } from "./context.ts"; import type { Method } from "./router.ts"; -export interface Render { +export interface PageResponse { data: T; + headers: Headers; + status: number; +} + +/** + * Create a {@link PageResponse} object that can be returned from a route + * handler. This will cause the page component to be rendered with the specified + * data and response options. + * + * ```ts + * export const handlers = define.handlers({ + * GET: (ctx) => { + * return page({ message: "Hello, world!" }, { + * headers: { "Cache-Control": "public, max-age=3600" }, + * status: 201, + * }); + * }, + * }); + * + * export default define.page(({ data }) => { + * return

{data.message}

; + * }); + * ``` + * + * @param data The data to pass to the page component to be rendered. + * @param options Additional options to use when constructing the response object. + * @returns A {@link PageResponse} object that should be returned from a route handler. + */ +export function page(data: T, options?: { headers?: HeadersInit; status?: number; +}): PageResponse; +export function page(): PageResponse; +export function page(data?: T, options?: { + headers?: HeadersInit; + status?: number; +}): PageResponse { + return { + data: data ?? undefined as T, + headers: options?.headers instanceof Headers + ? options.headers + : new Headers(options?.headers), + status: options?.status ?? 200, + }; } /** @@ -152,9 +194,8 @@ export function isHandlerByMethod( export interface HandlerFn { (ctx: FreshContext): | Response - | Render - | void - | Promise | void>; + | PageResponse + | Promise>; } /** diff --git a/src/mod.ts b/src/mod.ts index 8aa87cb3..f71a72a5 100644 --- a/src/mod.ts +++ b/src/mod.ts @@ -4,7 +4,8 @@ export { fsRoutes, type FsRoutesOptions } from "./plugins/fs_routes/mod.ts"; export { type HandlerByMethod, type HandlerFn, - type Render, + page, + type PageResponse, type RouteData, type RouteHandler, } from "./handlers.ts"; diff --git a/src/plugins/fs_routes/mod_test.tsx b/src/plugins/fs_routes/mod_test.tsx index e1ebf0b4..262e377b 100644 --- a/src/plugins/fs_routes/mod_test.tsx +++ b/src/plugins/fs_routes/mod_test.tsx @@ -9,7 +9,7 @@ import { import { delay, FakeServer } from "../../test_utils.ts"; import { createFakeFs } from "../../test_utils.ts"; import { expect } from "@std/expect"; -import type { HandlerByMethod, HandlerFn } from "../../handlers.ts"; +import { type HandlerByMethod, type HandlerFn, page } from "../../handlers.ts"; import type { Method } from "../../router.ts"; import { parseHtml } from "../../../tests/test_utils.tsx"; @@ -544,7 +544,7 @@ Deno.test("fsRoutes - handler return data", async () => { const server = await createServer({ "routes/index.tsx": { handler: () => { - return { data: "foo", status: 404 }; + return page("foo", { status: 404 }); }, default: (ctx) => { // deno-lint-ignore no-explicit-any diff --git a/src/plugins/fs_routes/render_middleware.ts b/src/plugins/fs_routes/render_middleware.ts index 7f191133..85a39286 100644 --- a/src/plugins/fs_routes/render_middleware.ts +++ b/src/plugins/fs_routes/render_middleware.ts @@ -1,6 +1,6 @@ import { type AnyComponent, h, type RenderableProps, type VNode } from "preact"; import type { MiddlewareFn } from "../../middlewares/mod.ts"; -import type { HandlerFn, Render } from "../../handlers.ts"; +import type { HandlerFn, PageResponse } from "../../handlers.ts"; import type { PageProps } from "../../runtime/server/mod.tsx"; export type AsyncAnyComponent

= { @@ -22,7 +22,7 @@ export function renderMiddleware( handler: HandlerFn | undefined, ): MiddlewareFn { return async (ctx) => { - let result: Render | undefined; + let result: PageResponse | undefined; if (handler !== undefined) { const res = await handler(ctx); diff --git a/www/routes/_app.tsx b/www/routes/_app.tsx index 37b9ceea..65998fb2 100644 --- a/www/routes/_app.tsx +++ b/www/routes/_app.tsx @@ -1,7 +1,7 @@ import { asset } from "@fresh/core/runtime"; -import { df } from "../utils/state.ts"; +import { define } from "../utils/state.ts"; -export default df.page(function App({ Component, state, url }) { +export default define.page(function App({ Component, state, url }) { return ( diff --git a/www/routes/docs/[...slug].tsx b/www/routes/docs/[...slug].tsx index 86bd5979..e4d72d49 100644 --- a/www/routes/docs/[...slug].tsx +++ b/www/routes/docs/[...slug].tsx @@ -1,4 +1,4 @@ -import { type Handlers, HttpError, type PageProps } from "@fresh/core"; +import { HttpError, page } from "@fresh/core"; import { asset, Partial } from "@fresh/core/runtime"; import { SidebarCategory } from "../../components/DocsSidebar.tsx"; import Footer from "../../components/Footer.tsx"; @@ -15,6 +15,7 @@ import toc from "../../../docs/toc.ts"; import { TableOfContents } from "../../islands/TableOfContents.tsx"; import SearchButton from "../../islands/SearchButton.tsx"; import VersionSelect from "../../islands/VersionSelect.tsx"; +import { define } from "../../utils/state.ts"; interface Data { page: Page; @@ -43,7 +44,7 @@ interface Page extends TableOfContentsEntry { const pattern = new URLPattern({ pathname: "/:version/:page*" }); -export const handler: Handlers = { +export const handler = define.handlers({ async GET(ctx) { const slug = ctx.params.slug; @@ -61,20 +62,20 @@ export const handler: Handlers = { throw new HttpError(404); } - let { version, page = "" } = match.pathname.groups; + let { version, page: path = "" } = match.pathname.groups; if (!version) { throw new HttpError(404); } // Latest version doesn't show up in the url if (!TABLE_OF_CONTENTS[version]) { - page = version + (page ? "/" + page : ""); + path = version + (path ? "/" + path : ""); version = LATEST_VERSION; } // Check if the page exists const currentToc = TABLE_OF_CONTENTS[version]; - const entry = currentToc[page]; + const entry = currentToc[path]; if (!entry) { throw new HttpError(404); } @@ -83,7 +84,7 @@ export const handler: Handlers = { const versionLinks: VersionLink[] = []; for (const version in TABLE_OF_CONTENTS) { const label = toc[version].label; - const maybeEntry = TABLE_OF_CONTENTS[version][page]; + const maybeEntry = TABLE_OF_CONTENTS[version][path]; // Check if the same page is available for this version and // link to that. Pick the index page for that version if an @@ -128,23 +129,21 @@ export const handler: Handlers = { : "Fresh Document"; ctx.state.ogImage = new URL(asset("/og-image.webp"), ctx.url).href; - return { - data: { - page: { - ...entry, - markdown: body, - data: attrs ?? {}, - versionLinks, - version, - prevNav, - nextNav, - }, + return page({ + page: { + ...entry, + markdown: body, + data: attrs ?? {}, + versionLinks, + version, + prevNav, + nextNav, }, - }; + }); }, -}; +}); -export default function DocsPage(props: PageProps) { +export default define.page(function DocsPage(props) { const { page } = props.data; const { html, headings } = renderMarkdown(page.markdown); @@ -241,7 +240,7 @@ export default function DocsPage(props: PageProps) { ); -} +}); function MobileSidebar({ page }: { page: Page }) { return ( diff --git a/www/routes/index.tsx b/www/routes/index.tsx index 2fe89aac..890f8fe8 100644 --- a/www/routes/index.tsx +++ b/www/routes/index.tsx @@ -1,5 +1,5 @@ import { asset } from "@fresh/core/runtime"; -import type { Handlers, PageProps } from "@fresh/core"; +import { page } from "@fresh/core"; import VERSIONS from "../../versions.json" with { type: "json" }; import Footer from "../components/Footer.tsx"; import Header from "../components/Header.tsx"; @@ -12,9 +12,9 @@ import { FormsSection } from "../components/homepage/FormsSection.tsx"; import { Simple } from "../components/homepage/Simple.tsx"; import { SocialProof } from "../components/homepage/SocialProof.tsx"; import { DenoSection } from "../components/homepage/DenoSection.tsx"; -import { df } from "../utils/state.ts"; +import { define } from "../utils/state.ts"; -export const handler = df.handlers({ +export const handler = define.handlers({ GET(ctx) { const { req } = ctx; const accept = req.headers.get("accept"); @@ -32,6 +32,8 @@ export const handler = df.handlers({ ctx.state.description = "Fresh features just-in-time edge rendering, island based interactivity, and zero-configuration TypeScript support. Fast to write; fast to run."; ctx.state.ogImage = new URL(asset("/og-image.webp"), ctx.url).href; + + return page(); }, async POST(ctx) { const headers = new Headers(); @@ -45,7 +47,7 @@ export const handler = df.handlers({ }, }); -export default function MainPage(props: PageProps) { +export default define.page(function MainPage(props) { const origin = `${props.url.protocol}//${props.url.host}`; return ( @@ -68,7 +70,7 @@ export default function MainPage(props: PageProps) {