diff --git a/docs/concepts/data-fetching.md b/docs/concepts/data-fetching.md index 17eaa7b0..6581d802 100644 --- a/docs/concepts/data-fetching.md +++ b/docs/concepts/data-fetching.md @@ -16,7 +16,7 @@ interface Project { stars: number; } -export const handler: MultiHandler = { +export const handler: Handlers = { async GET(_req, ctx) { const project = await db.projects.findOne({ id: ctx.params.id }); if (!project) { @@ -36,7 +36,7 @@ export default function ProjectPage(props: PageProps) { } ``` -The type parameter on the `PageProps`, `MultiHandler`, `Handler`, and +The type parameter on the `PageProps`, `Handlers`, `Handler`, and `HandlerContext` can be used to enforce a TypeScript type to use for the render data. Fresh enforces during type checking that the types in all of these fields are compatible within a single page. diff --git a/docs/concepts/error-pages.md b/docs/concepts/error-pages.md index 32463873..dc5cd30d 100644 --- a/docs/concepts/error-pages.md +++ b/docs/concepts/error-pages.md @@ -30,9 +30,9 @@ example when the route did match, but the requested resource does not exist. This can be achieved with `ctx.renderNotFound`. ```tsx -import { MultiHandler, PageProps } from "$fresh/server.ts"; +import { Handlers, PageProps } from "$fresh/server.ts"; -export const handler: MultiHandler = { +export const handler: Handlers = { async GET(req, ctx) { const blogpost = await fetchBlogpost(ctx.params.slug); if (!blogpost) { diff --git a/docs/concepts/forms.md b/docs/concepts/forms.md index 5eff3787..c972a090 100644 --- a/docs/concepts/forms.md +++ b/docs/concepts/forms.md @@ -20,9 +20,9 @@ submissions: ```tsx // routes/subscribe.tsx -import { MultiHandler } from "$fresh/server.ts"; +import { Handlers } from "$fresh/server.ts"; -export const handler: MultiHandler = { +export const handler: Handlers = { async GET(req, ctx) { return await ctx.render(); }, diff --git a/docs/concepts/middleware.md b/docs/concepts/middleware.md index f2ae6680..23bc9f06 100644 --- a/docs/concepts/middleware.md +++ b/docs/concepts/middleware.md @@ -12,7 +12,7 @@ Each middleware gets passed a `next` function in the context argument that is used to trigger child handlers. The `ctx` also has a `state` property that can be used to pass arbitrary data to downstream (or upstream) handlers. This `state` is included in `PageProps` by default, which is available to both the -special [_app](/docs/concepts/app-wrapper.md) wrapper and normal +special [\_app](/docs/concepts/app-wrapper.md) wrapper and normal [routes](/docs/concepts/routes.md). ```ts @@ -36,7 +36,7 @@ export async function handler( ```ts // routes/myHandler.ts -export const handler: MultiHandler = { +export const handler: Handlers = { GET(_req, ctx) { return new Response(`middleware data is ${ctx.state.data}`); }, @@ -125,10 +125,7 @@ create a `_middleware.ts` file in the `routes` folder like this: ```ts import { MiddlewareHandlerContext } from "$fresh/server.ts"; -export async function handler( - req: Request, - ctx: MiddlewareHandlerContext, -) { +export async function handler(req: Request, ctx: MiddlewareHandlerContext) { console.log(ctx.destination); console.log(req.url); const resp = await ctx.next(); diff --git a/docs/concepts/routes.md b/docs/concepts/routes.md index d148100f..d3c2fa2d 100644 --- a/docs/concepts/routes.md +++ b/docs/concepts/routes.md @@ -28,9 +28,9 @@ Let's look at a basic route that returns a plain text string: ```tsx // routes/plain.tsx -import { HandlerContext, MultiHandler } from "$fresh/server.ts"; +import { HandlerContext, Handlers } from "$fresh/server.ts"; -export const handler: MultiHandler = { +export const handler: Handlers = { GET(_req: Request, _ctx: HandlerContext) { return new Response("Hello World"); }, @@ -74,9 +74,9 @@ response after rendering the page component. ```tsx // routes/html.tsx -import { HandlerContext, MultiHandler, PageProps } from "$fresh/server.ts"; +import { HandlerContext, Handlers, PageProps } from "$fresh/server.ts"; -export const handler: MultiHandler = { +export const handler: Handlers = { async GET(_req: Request, ctx: HandlerContext) { const resp = await ctx.render(); resp.headers.set("X-Custom-Header", "Hello World"); diff --git a/docs/examples/writing-tests.md b/docs/examples/writing-tests.md index 549d311f..7d5a251a 100644 --- a/docs/examples/writing-tests.md +++ b/docs/examples/writing-tests.md @@ -12,9 +12,9 @@ through ```tsx // routes/index.tsx -import { MultiHandler } from "$fresh/server.ts"; +import { Handlers } from "$fresh/server.ts"; -export const handler: MultiHandler = { +export const handler: Handlers = { async POST(req) { const form = await req.formData(); diff --git a/docs/getting-started/custom-handlers.md b/docs/getting-started/custom-handlers.md index 32093a85..169803df 100644 --- a/docs/getting-started/custom-handlers.md +++ b/docs/getting-started/custom-handlers.md @@ -7,7 +7,7 @@ description: | Routes actually consist of two parts: handlers, and the page component. Up to now, only the page component has been discussed in this chapter. -MultiHandler are functions in the form of `Request => Response` or +Handlers are functions in the form of `Request => Response` or `Request => Promise` that are called when a request is made to a particular route. There can be one handler that covers all HTTP methods or one handler per method. @@ -20,9 +20,9 @@ define a custom handler use a default handler that just renders the page component. To define a handler in a route module, one must export it as a named export with -the name `handler`. MultiHandler can have two forms: a plain function (catchall -for all HTTP methods) or a plain object where each property is a function named -by the HTTP method it handles. +the name `handler`. Handlers can have two forms: a plain function (catchall for +all HTTP methods) or a plain object where each property is a function named by +the HTTP method it handles. Here is an example of a custom `GET` handler that renders the page component and then adds a custom header to the response before returning it: @@ -30,9 +30,9 @@ then adds a custom header to the response before returning it: ```tsx // routes/about.tsx -import { MultiHandler } from "$fresh/server.ts"; +import { Handlers } from "$fresh/server.ts"; -export const handler: MultiHandler = { +export const handler: Handlers = { async GET(_req, ctx) { const resp = await ctx.render(); resp.headers.set("X-Custom-Header", "Hello"); @@ -57,9 +57,9 @@ response: ```ts // routes/api/random-uuid.ts -import { MultiHandler } from "$fresh/server.ts"; +import { Handlers } from "$fresh/server.ts"; -export const handler: MultiHandler = { +export const handler: Handlers = { GET(_req) { const uuid = crypto.randomUUID(); return new Response(JSON.stringify(uuid), { diff --git a/docs/getting-started/fetching-data.md b/docs/getting-started/fetching-data.md index 71e69a2b..7716e6c7 100644 --- a/docs/getting-started/fetching-data.md +++ b/docs/getting-started/fetching-data.md @@ -1,7 +1,7 @@ --- description: | Fetch data for routes dynamically by creating a custom handler and passing - data to the render function. + data to the render function. --- All of the pages in the demo project so far have not used any dynamic data @@ -23,7 +23,7 @@ renders it in a page component. ```tsx // routes/github/[username].tsx -import { MultiHandler, PageProps } from "$fresh/server.ts"; +import { Handlers, PageProps } from "$fresh/server.ts"; interface User { login: string; @@ -31,7 +31,7 @@ interface User { avatar_url: string; } -export const handler: MultiHandler = { +export const handler: Handlers = { async GET(_, ctx) { const { username } = ctx.params; const resp = await fetch(`https://api.github.com/users/${username}`); diff --git a/docs/getting-started/form-submissions.md b/docs/getting-started/form-submissions.md index 78efb12a..c566ee68 100644 --- a/docs/getting-started/form-submissions.md +++ b/docs/getting-started/form-submissions.md @@ -32,7 +32,7 @@ server side: ```tsx // routes/search.tsx -import { MultiHandler, PageProps } from "$fresh/server.ts"; +import { Handlers, PageProps } from "$fresh/server.ts"; const NAMES = ["Alice", "Bob", "Charlie", "Dave", "Eve", "Frank"]; @@ -41,7 +41,7 @@ interface Data { query: string; } -export const handler: MultiHandler = { +export const handler: Handlers = { GET(req, ctx) { const url = new URL(req.url); const query = url.searchParams.get("q") || ""; diff --git a/src/server/context.ts b/src/server/context.ts index c36d537d..b24e2739 100644 --- a/src/server/context.ts +++ b/src/server/context.ts @@ -192,6 +192,11 @@ export class ServerContext { pattern = String(config.routeOverride); } let { handler } = module as RouteModule; + if (!handler && "handlers" in module) { + throw new Error( + `Found named export "handlers" in ${self} instead of "handler". Did you mean "handler"?`, + ); + } handler ??= {}; if ( component && typeof handler === "object" && handler.GET === undefined diff --git a/src/server/types.ts b/src/server/types.ts index 093622f5..77e7c6aa 100644 --- a/src/server/types.ts +++ b/src/server/types.ts @@ -103,19 +103,19 @@ export type Handler> = ( ) => Response | Promise; // deno-lint-ignore no-explicit-any -export type MultiHandler> = { +export type Handlers> = { [K in router.KnownMethod]?: Handler; }; /** - * @deprecated This type has been deprecated and is replaced with MultiHandler type. + * @deprecated This type was a short-lived alternative to `Handlers`. Please use `Handlers` instead. */ -export type Handlers = MultiHandler; +export type MultiHandler = Handlers; export interface RouteModule { default?: ComponentType; // deno-lint-ignore no-explicit-any - handler?: Handler | MultiHandler; + handler?: Handler | Handlers; config?: RouteConfig; } @@ -125,7 +125,7 @@ export interface Route { url: string; name: string; component?: ComponentType>; - handler: Handler | MultiHandler; + handler: Handler | Handlers; csp: boolean; } diff --git a/tests/fixture/routes/connInfo.ts b/tests/fixture/routes/connInfo.ts index 3beb0863..f493400c 100644 --- a/tests/fixture/routes/connInfo.ts +++ b/tests/fixture/routes/connInfo.ts @@ -1,6 +1,6 @@ -import { MultiHandler } from "../../../server.ts"; +import { Handlers } from "../../../server.ts"; -export const handler: MultiHandler = { +export const handler: Handlers = { GET(_req, ctx) { return new Response((ctx.remoteAddr as Deno.NetAddr).hostname); }, diff --git a/tests/fixture/routes/intercept_args.tsx b/tests/fixture/routes/intercept_args.tsx index 0b61af76..64c2781f 100644 --- a/tests/fixture/routes/intercept_args.tsx +++ b/tests/fixture/routes/intercept_args.tsx @@ -1,4 +1,4 @@ -import { MultiHandler, PageProps } from "$fresh/server.ts"; +import { Handlers, PageProps } from "$fresh/server.ts"; interface Data extends Record { info: string; @@ -8,7 +8,7 @@ export default function Page({ data }: PageProps) { return
{data.info}
; } -export const handler: MultiHandler = { +export const handler: Handlers = { GET(req, { render }) { if (req.headers.get("accept")?.includes("text/html")) { return render({ diff --git a/tests/fixture/routes/layeredMdw/layer2-no-mw/without_mw.ts b/tests/fixture/routes/layeredMdw/layer2-no-mw/without_mw.ts index 94f2a522..650e9be8 100644 --- a/tests/fixture/routes/layeredMdw/layer2-no-mw/without_mw.ts +++ b/tests/fixture/routes/layeredMdw/layer2-no-mw/without_mw.ts @@ -1,4 +1,4 @@ -import { MultiHandler } from "../../../../../server.ts"; +import { Handlers } from "../../../../../server.ts"; interface State { root: string; @@ -6,7 +6,7 @@ interface State { layer3: string; } -export const handler: MultiHandler = { +export const handler: Handlers = { GET(_req: Request, { state }) { return new Response(JSON.stringify(state)); }, diff --git a/tests/fixture/routes/layeredMdw/layer2/abc.ts b/tests/fixture/routes/layeredMdw/layer2/abc.ts index 79e1bcfe..2be04d06 100644 --- a/tests/fixture/routes/layeredMdw/layer2/abc.ts +++ b/tests/fixture/routes/layeredMdw/layer2/abc.ts @@ -1,4 +1,4 @@ -import { MultiHandler } from "../../../../../server.ts"; +import { Handlers } from "../../../../../server.ts"; interface State { root: string; @@ -6,7 +6,7 @@ interface State { layer2: string; } -export const handler: MultiHandler = { +export const handler: Handlers = { GET(_req: Request, { state }) { return new Response(JSON.stringify(state)); }, diff --git a/tests/fixture/routes/layeredMdw/layer2/index.ts b/tests/fixture/routes/layeredMdw/layer2/index.ts index 79e1bcfe..2be04d06 100644 --- a/tests/fixture/routes/layeredMdw/layer2/index.ts +++ b/tests/fixture/routes/layeredMdw/layer2/index.ts @@ -1,4 +1,4 @@ -import { MultiHandler } from "../../../../../server.ts"; +import { Handlers } from "../../../../../server.ts"; interface State { root: string; @@ -6,7 +6,7 @@ interface State { layer2: string; } -export const handler: MultiHandler = { +export const handler: Handlers = { GET(_req: Request, { state }) { return new Response(JSON.stringify(state)); }, diff --git a/tests/fixture/routes/layeredMdw/layer2/layer3/[id].ts b/tests/fixture/routes/layeredMdw/layer2/layer3/[id].ts index d3c64fac..986a7ca3 100644 --- a/tests/fixture/routes/layeredMdw/layer2/layer3/[id].ts +++ b/tests/fixture/routes/layeredMdw/layer2/layer3/[id].ts @@ -1,4 +1,4 @@ -import { MultiHandler } from "../../../../../../server.ts"; +import { Handlers } from "../../../../../../server.ts"; interface State { root: string; @@ -7,7 +7,7 @@ interface State { layer3: string; } -export const handler: MultiHandler = { +export const handler: Handlers = { GET(_req: Request, { state }) { return new Response(JSON.stringify(state)); }, diff --git a/tests/fixture/routes/middleware_root.ts b/tests/fixture/routes/middleware_root.ts index 6c4f4221..78340640 100644 --- a/tests/fixture/routes/middleware_root.ts +++ b/tests/fixture/routes/middleware_root.ts @@ -1,10 +1,10 @@ -import { MultiHandler } from "../../../server.ts"; +import { Handlers } from "../../../server.ts"; interface State { root: string; } -export const handler: MultiHandler = { +export const handler: Handlers = { GET(_req: Request, { state }) { return new Response(JSON.stringify(state)); }, diff --git a/tests/fixture/routes/not_found.ts b/tests/fixture/routes/not_found.ts index cda74425..b90959d5 100644 --- a/tests/fixture/routes/not_found.ts +++ b/tests/fixture/routes/not_found.ts @@ -1,6 +1,6 @@ -import { MultiHandler } from "../../../server.ts"; +import { Handlers } from "../../../server.ts"; -export const handler: MultiHandler = { +export const handler: Handlers = { GET(_req, ctx) { return ctx.renderNotFound({ hello: "Dino", diff --git a/tests/fixture_error/routes/[...all].ts b/tests/fixture_error/routes/[...all].ts index 7e1577f1..dd4355b9 100644 --- a/tests/fixture_error/routes/[...all].ts +++ b/tests/fixture_error/routes/[...all].ts @@ -1,6 +1,6 @@ -import { MultiHandler } from "../../../server.ts"; +import { Handlers } from "../../../server.ts"; -export const handler: MultiHandler = { +export const handler: Handlers = { GET(_req, ctx) { return new Response(ctx.params.all); }, diff --git a/tests/fixture_invalid_handlers/deno.json b/tests/fixture_invalid_handlers/deno.json new file mode 100644 index 00000000..fa257c4d --- /dev/null +++ b/tests/fixture_invalid_handlers/deno.json @@ -0,0 +1,13 @@ +{ + "lock": false, + "imports": { + "$fresh/": "../../", + "preact": "https://esm.sh/preact@10.15.1", + "preact/": "https://esm.sh/preact@10.15.1/", + "preact-render-to-string": "https://esm.sh/*preact-render-to-string@6.1.0" + }, + "compilerOptions": { + "jsx": "react-jsx", + "jsxImportSource": "preact" + } +} diff --git a/tests/fixture_invalid_handlers/dev.ts b/tests/fixture_invalid_handlers/dev.ts new file mode 100755 index 00000000..2d85d6c1 --- /dev/null +++ b/tests/fixture_invalid_handlers/dev.ts @@ -0,0 +1,5 @@ +#!/usr/bin/env -S deno run -A --watch=static/,routes/ + +import dev from "$fresh/dev.ts"; + +await dev(import.meta.url, "./main.ts"); diff --git a/tests/fixture_invalid_handlers/fresh.gen.ts b/tests/fixture_invalid_handlers/fresh.gen.ts new file mode 100644 index 00000000..799a93fb --- /dev/null +++ b/tests/fixture_invalid_handlers/fresh.gen.ts @@ -0,0 +1,15 @@ +// DO NOT EDIT. This file is generated by fresh. +// This file SHOULD be checked into source version control. +// This file is automatically updated during development when running `dev.ts`. + +import * as $0 from "./routes/index.tsx"; + +const manifest = { + routes: { + "./routes/index.tsx": $0, + }, + islands: {}, + baseUrl: import.meta.url, +}; + +export default manifest; diff --git a/tests/fixture_invalid_handlers/main.ts b/tests/fixture_invalid_handlers/main.ts new file mode 100644 index 00000000..dedce9cb --- /dev/null +++ b/tests/fixture_invalid_handlers/main.ts @@ -0,0 +1,10 @@ +/// +/// +/// +/// +/// + +import { start } from "$fresh/server.ts"; +import manifest from "./fresh.gen.ts"; + +await start(manifest); diff --git a/tests/fixture_invalid_handlers/routes/index.tsx b/tests/fixture_invalid_handlers/routes/index.tsx new file mode 100644 index 00000000..385b9164 --- /dev/null +++ b/tests/fixture_invalid_handlers/routes/index.tsx @@ -0,0 +1,7 @@ +import { Handlers } from "../../../server.ts"; + +export const handlers: Handlers = { + GET() { + throw new Error("FAIL"); + }, +}; diff --git a/tests/main_test.ts b/tests/main_test.ts index 4514187f..0aaa54ed 100644 --- a/tests/main_test.ts +++ b/tests/main_test.ts @@ -10,6 +10,7 @@ import manifest from "./fixture/fresh.gen.ts"; import options from "./fixture/options.ts"; import { BUILD_ID } from "../src/server/build_id.ts"; import { startFreshServer } from "./test_utils.ts"; +import { assertMatch } from "https://deno.land/std@0.190.0/testing/asserts.ts"; const ctx = await ServerContext.fromManifest(manifest, options); const handler = ctx.handler(); @@ -815,6 +816,22 @@ Deno.test("PORT environment variable", { serverProcess.kill("SIGTERM"); }); +Deno.test("throw on route export 'handlers' instead of 'handler'", { + sanitizeOps: false, + sanitizeResources: false, +}, async () => { + const result = await new Deno.Command(Deno.execPath(), { + args: ["run", "-A", "./tests/fixture_invalid_handlers/main.ts"], + stderr: "piped", + stdout: "piped", + }).output(); + + assertEquals(result.code, 1); + + const text = new TextDecoder().decode(result.stderr); + assertMatch(text, /Did you mean "handler"\?/); +}); + Deno.test("rendering custom _500.tsx page for default handlers", { sanitizeOps: false, sanitizeResources: false, diff --git a/www/routes/components.tsx b/www/routes/components.tsx index f7e6c2f3..7aeda47a 100644 --- a/www/routes/components.tsx +++ b/www/routes/components.tsx @@ -3,13 +3,13 @@ import Header from "../components/Header.tsx"; import ComponentGallery from "../islands/ComponentGallery.tsx"; import { asset, Head } from "$fresh/runtime.ts"; -import { MultiHandler, PageProps } from "$fresh/server.ts"; +import { Handlers, PageProps } from "$fresh/server.ts"; function getSource(path: string) { return Deno.readTextFile(new URL(path, import.meta.url)); } -export const handler: MultiHandler = { +export const handler: Handlers = { async GET(req, ctx) { const props: HomeProps = { sources: { diff --git a/www/routes/docs/[...slug].tsx b/www/routes/docs/[...slug].tsx index af09fe2d..c612cc3d 100644 --- a/www/routes/docs/[...slug].tsx +++ b/www/routes/docs/[...slug].tsx @@ -1,5 +1,5 @@ import { asset, Head } from "$fresh/runtime.ts"; -import { MultiHandler, PageProps } from "$fresh/server.ts"; +import { Handlers, PageProps } from "$fresh/server.ts"; import { frontMatter, gfm } from "../../utils/markdown.ts"; import Header from "../../components/Header.tsx"; @@ -21,7 +21,7 @@ interface Page extends TableOfContentsEntry { data: Record; } -export const handler: MultiHandler = { +export const handler: Handlers = { async GET(_req, ctx) { const slug = ctx.params.slug; if (slug === "") { diff --git a/www/routes/gfm.css.ts b/www/routes/gfm.css.ts index 2ca739d4..24818465 100644 --- a/www/routes/gfm.css.ts +++ b/www/routes/gfm.css.ts @@ -1,4 +1,4 @@ -import { MultiHandler } from "$fresh/server.ts"; +import { Handlers } from "$fresh/server.ts"; import { gfm } from "../utils/markdown.ts"; // TODO(lucacasonato): hash the file and use the hash as the filename, and serve @@ -36,7 +36,7 @@ ol.nested li:before { } `; -export const handler: MultiHandler = { +export const handler: Handlers = { GET: () => { return new Response(CSS, { headers: { diff --git a/www/routes/index.tsx b/www/routes/index.tsx index 58d01988..ac363263 100644 --- a/www/routes/index.tsx +++ b/www/routes/index.tsx @@ -1,5 +1,5 @@ import { asset, Head } from "$fresh/runtime.ts"; -import { MultiHandler, PageProps } from "$fresh/server.ts"; +import { Handlers, PageProps } from "$fresh/server.ts"; import Counter from "../islands/Counter.tsx"; import LemonDrop from "../islands/LemonDrop.tsx"; import Footer from "../components/Footer.tsx"; @@ -18,7 +18,7 @@ function isOpenGraphUA(header: string | null): boolean { return header.startsWith("Twitterbot") || header.startsWith("Slackbot"); } -export const handler: MultiHandler = { +export const handler: Handlers = { GET(req, ctx) { const accept = req.headers.get("accept"); const userAgent = req.headers.get("user-agent"); diff --git a/www/routes/raw.ts b/www/routes/raw.ts index a0f08145..2bc3bbc8 100644 --- a/www/routes/raw.ts +++ b/www/routes/raw.ts @@ -1,5 +1,5 @@ import { RouteConfig } from "$fresh/server.ts"; -import { MultiHandler } from "$fresh/server.ts"; +import { Handlers } from "$fresh/server.ts"; import { parse } from "$std/semver/mod.ts"; import VERSIONS from "../../versions.json" assert { type: "json" }; import { extname } from "$std/path/mod.ts"; @@ -16,7 +16,7 @@ const contentTypes = new Map([ [".wasm", "application/wasm"], ]); -export const handler: MultiHandler = { +export const handler: Handlers = { async GET(req, ctx) { const accept = req.headers.get("Accept"); const isHTML = accept?.includes("text/html"); diff --git a/www/routes/update.tsx b/www/routes/update.tsx index f11e8556..0a7c15e9 100644 --- a/www/routes/update.tsx +++ b/www/routes/update.tsx @@ -1,7 +1,7 @@ -import { MultiHandler, PageProps } from "$fresh/server.ts"; +import { Handlers, PageProps } from "$fresh/server.ts"; import VERSIONS from "../../versions.json" assert { type: "json" }; -export const handler: MultiHandler = { +export const handler: Handlers = { GET(req) { const accept = req.headers.get("accept"); let path = "/docs/concepts/updating";