fix: change MultiHandler back to Handlers (#1396)

This commit is contained in:
Marvin Hagemeister
2023-07-03 09:57:46 +02:00
committed by GitHub
parent eb53d53ab8
commit 16be99e69b
32 changed files with 135 additions and 66 deletions
+2 -2
View File
@@ -16,7 +16,7 @@ interface Project {
stars: number; stars: number;
} }
export const handler: MultiHandler<Project> = { export const handler: Handlers<Project> = {
async GET(_req, ctx) { async GET(_req, ctx) {
const project = await db.projects.findOne({ id: ctx.params.id }); const project = await db.projects.findOne({ id: ctx.params.id });
if (!project) { if (!project) {
@@ -36,7 +36,7 @@ export default function ProjectPage(props: PageProps<Project>) {
} }
``` ```
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 `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 data. Fresh enforces during type checking that the types in all of these fields
are compatible within a single page. are compatible within a single page.
+2 -2
View File
@@ -30,9 +30,9 @@ example when the route did match, but the requested resource does not exist.
This can be achieved with `ctx.renderNotFound`. This can be achieved with `ctx.renderNotFound`.
```tsx ```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) { async GET(req, ctx) {
const blogpost = await fetchBlogpost(ctx.params.slug); const blogpost = await fetchBlogpost(ctx.params.slug);
if (!blogpost) { if (!blogpost) {
+2 -2
View File
@@ -20,9 +20,9 @@ submissions:
```tsx ```tsx
// routes/subscribe.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) { async GET(req, ctx) {
return await ctx.render(); return await ctx.render();
}, },
+3 -6
View File
@@ -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 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 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 `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). [routes](/docs/concepts/routes.md).
```ts ```ts
@@ -36,7 +36,7 @@ export async function handler(
```ts ```ts
// routes/myHandler.ts // routes/myHandler.ts
export const handler: MultiHandler<any, { data: string }> = { export const handler: Handlers<any, { data: string }> = {
GET(_req, ctx) { GET(_req, ctx) {
return new Response(`middleware data is ${ctx.state.data}`); 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 ```ts
import { MiddlewareHandlerContext } from "$fresh/server.ts"; import { MiddlewareHandlerContext } from "$fresh/server.ts";
export async function handler( export async function handler(req: Request, ctx: MiddlewareHandlerContext) {
req: Request,
ctx: MiddlewareHandlerContext,
) {
console.log(ctx.destination); console.log(ctx.destination);
console.log(req.url); console.log(req.url);
const resp = await ctx.next(); const resp = await ctx.next();
+4 -4
View File
@@ -28,9 +28,9 @@ Let's look at a basic route that returns a plain text string:
```tsx ```tsx
// routes/plain.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) { GET(_req: Request, _ctx: HandlerContext) {
return new Response("Hello World"); return new Response("Hello World");
}, },
@@ -74,9 +74,9 @@ response after rendering the page component.
```tsx ```tsx
// routes/html.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) { async GET(_req: Request, ctx: HandlerContext) {
const resp = await ctx.render(); const resp = await ctx.render();
resp.headers.set("X-Custom-Header", "Hello World"); resp.headers.set("X-Custom-Header", "Hello World");
+2 -2
View File
@@ -12,9 +12,9 @@ through
```tsx ```tsx
// routes/index.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) { async POST(req) {
const form = await req.formData(); const form = await req.formData();
+8 -8
View File
@@ -7,7 +7,7 @@ description: |
Routes actually consist of two parts: handlers, and the page component. Up to Routes actually consist of two parts: handlers, and the page component. Up to
now, only the page component has been discussed in this chapter. 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<Response>` that are called when a request is made to a `Request => Promise<Response>` that are called when a request is made to a
particular route. There can be one handler that covers all HTTP methods or one particular route. There can be one handler that covers all HTTP methods or one
handler per method. handler per method.
@@ -20,9 +20,9 @@ define a custom handler use a default handler that just renders the page
component. component.
To define a handler in a route module, one must export it as a named export with 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 the name `handler`. Handlers can have two forms: a plain function (catchall for
for all HTTP methods) or a plain object where each property is a function named all HTTP methods) or a plain object where each property is a function named by
by the HTTP method it handles. the HTTP method it handles.
Here is an example of a custom `GET` handler that renders the page component and 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: 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 ```tsx
// routes/about.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) { async GET(_req, ctx) {
const resp = await ctx.render(); const resp = await ctx.render();
resp.headers.set("X-Custom-Header", "Hello"); resp.headers.set("X-Custom-Header", "Hello");
@@ -57,9 +57,9 @@ response:
```ts ```ts
// routes/api/random-uuid.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) { GET(_req) {
const uuid = crypto.randomUUID(); const uuid = crypto.randomUUID();
return new Response(JSON.stringify(uuid), { return new Response(JSON.stringify(uuid), {
+3 -3
View File
@@ -1,7 +1,7 @@
--- ---
description: | description: |
Fetch data for routes dynamically by creating a custom handler and passing 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 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 ```tsx
// routes/github/[username].tsx // routes/github/[username].tsx
import { MultiHandler, PageProps } from "$fresh/server.ts"; import { Handlers, PageProps } from "$fresh/server.ts";
interface User { interface User {
login: string; login: string;
@@ -31,7 +31,7 @@ interface User {
avatar_url: string; avatar_url: string;
} }
export const handler: MultiHandler<User | null> = { export const handler: Handlers<User | null> = {
async GET(_, ctx) { async GET(_, ctx) {
const { username } = ctx.params; const { username } = ctx.params;
const resp = await fetch(`https://api.github.com/users/${username}`); const resp = await fetch(`https://api.github.com/users/${username}`);
+2 -2
View File
@@ -32,7 +32,7 @@ server side:
```tsx ```tsx
// routes/search.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"]; const NAMES = ["Alice", "Bob", "Charlie", "Dave", "Eve", "Frank"];
@@ -41,7 +41,7 @@ interface Data {
query: string; query: string;
} }
export const handler: MultiHandler<Data> = { export const handler: Handlers<Data> = {
GET(req, ctx) { GET(req, ctx) {
const url = new URL(req.url); const url = new URL(req.url);
const query = url.searchParams.get("q") || ""; const query = url.searchParams.get("q") || "";
+5
View File
@@ -192,6 +192,11 @@ export class ServerContext {
pattern = String(config.routeOverride); pattern = String(config.routeOverride);
} }
let { handler } = module as RouteModule; 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 ??= {}; handler ??= {};
if ( if (
component && typeof handler === "object" && handler.GET === undefined component && typeof handler === "object" && handler.GET === undefined
+5 -5
View File
@@ -103,19 +103,19 @@ export type Handler<T = any, State = Record<string, unknown>> = (
) => Response | Promise<Response>; ) => Response | Promise<Response>;
// deno-lint-ignore no-explicit-any // deno-lint-ignore no-explicit-any
export type MultiHandler<T = any, State = Record<string, unknown>> = { export type Handlers<T = any, State = Record<string, unknown>> = {
[K in router.KnownMethod]?: Handler<T, State>; [K in router.KnownMethod]?: Handler<T, State>;
}; };
/** /**
* @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<T> = MultiHandler<T>; export type MultiHandler<T> = Handlers<T>;
export interface RouteModule { export interface RouteModule {
default?: ComponentType<PageProps>; default?: ComponentType<PageProps>;
// deno-lint-ignore no-explicit-any // deno-lint-ignore no-explicit-any
handler?: Handler<any, any> | MultiHandler<any, any>; handler?: Handler<any, any> | Handlers<any, any>;
config?: RouteConfig; config?: RouteConfig;
} }
@@ -125,7 +125,7 @@ export interface Route<Data = any> {
url: string; url: string;
name: string; name: string;
component?: ComponentType<PageProps<Data>>; component?: ComponentType<PageProps<Data>>;
handler: Handler<Data> | MultiHandler<Data>; handler: Handler<Data> | Handlers<Data>;
csp: boolean; csp: boolean;
} }
+2 -2
View File
@@ -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) { GET(_req, ctx) {
return new Response((ctx.remoteAddr as Deno.NetAddr).hostname); return new Response((ctx.remoteAddr as Deno.NetAddr).hostname);
}, },
+2 -2
View File
@@ -1,4 +1,4 @@
import { MultiHandler, PageProps } from "$fresh/server.ts"; import { Handlers, PageProps } from "$fresh/server.ts";
interface Data extends Record<string, unknown> { interface Data extends Record<string, unknown> {
info: string; info: string;
@@ -8,7 +8,7 @@ export default function Page({ data }: PageProps<Data>) {
return <div>{data.info}</div>; return <div>{data.info}</div>;
} }
export const handler: MultiHandler<Data> = { export const handler: Handlers<Data> = {
GET(req, { render }) { GET(req, { render }) {
if (req.headers.get("accept")?.includes("text/html")) { if (req.headers.get("accept")?.includes("text/html")) {
return render({ return render({
@@ -1,4 +1,4 @@
import { MultiHandler } from "../../../../../server.ts"; import { Handlers } from "../../../../../server.ts";
interface State { interface State {
root: string; root: string;
@@ -6,7 +6,7 @@ interface State {
layer3: string; layer3: string;
} }
export const handler: MultiHandler<undefined, State> = { export const handler: Handlers<undefined, State> = {
GET(_req: Request, { state }) { GET(_req: Request, { state }) {
return new Response(JSON.stringify(state)); return new Response(JSON.stringify(state));
}, },
@@ -1,4 +1,4 @@
import { MultiHandler } from "../../../../../server.ts"; import { Handlers } from "../../../../../server.ts";
interface State { interface State {
root: string; root: string;
@@ -6,7 +6,7 @@ interface State {
layer2: string; layer2: string;
} }
export const handler: MultiHandler<undefined, State> = { export const handler: Handlers<undefined, State> = {
GET(_req: Request, { state }) { GET(_req: Request, { state }) {
return new Response(JSON.stringify(state)); return new Response(JSON.stringify(state));
}, },
@@ -1,4 +1,4 @@
import { MultiHandler } from "../../../../../server.ts"; import { Handlers } from "../../../../../server.ts";
interface State { interface State {
root: string; root: string;
@@ -6,7 +6,7 @@ interface State {
layer2: string; layer2: string;
} }
export const handler: MultiHandler<undefined, State> = { export const handler: Handlers<undefined, State> = {
GET(_req: Request, { state }) { GET(_req: Request, { state }) {
return new Response(JSON.stringify(state)); return new Response(JSON.stringify(state));
}, },
@@ -1,4 +1,4 @@
import { MultiHandler } from "../../../../../../server.ts"; import { Handlers } from "../../../../../../server.ts";
interface State { interface State {
root: string; root: string;
@@ -7,7 +7,7 @@ interface State {
layer3: string; layer3: string;
} }
export const handler: MultiHandler<undefined, State> = { export const handler: Handlers<undefined, State> = {
GET(_req: Request, { state }) { GET(_req: Request, { state }) {
return new Response(JSON.stringify(state)); return new Response(JSON.stringify(state));
}, },
+2 -2
View File
@@ -1,10 +1,10 @@
import { MultiHandler } from "../../../server.ts"; import { Handlers } from "../../../server.ts";
interface State { interface State {
root: string; root: string;
} }
export const handler: MultiHandler<undefined, State> = { export const handler: Handlers<undefined, State> = {
GET(_req: Request, { state }) { GET(_req: Request, { state }) {
return new Response(JSON.stringify(state)); return new Response(JSON.stringify(state));
}, },
+2 -2
View File
@@ -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) { GET(_req, ctx) {
return ctx.renderNotFound({ return ctx.renderNotFound({
hello: "Dino", hello: "Dino",
+2 -2
View File
@@ -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) { GET(_req, ctx) {
return new Response(ctx.params.all); return new Response(ctx.params.all);
}, },
+13
View File
@@ -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"
}
}
+5
View File
@@ -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");
@@ -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;
+10
View File
@@ -0,0 +1,10 @@
/// <reference no-default-lib="true" />
/// <reference lib="dom" />
/// <reference lib="dom.iterable" />
/// <reference lib="dom.asynciterable" />
/// <reference lib="deno.ns" />
import { start } from "$fresh/server.ts";
import manifest from "./fresh.gen.ts";
await start(manifest);
@@ -0,0 +1,7 @@
import { Handlers } from "../../../server.ts";
export const handlers: Handlers = {
GET() {
throw new Error("FAIL");
},
};
+17
View File
@@ -10,6 +10,7 @@ import manifest from "./fixture/fresh.gen.ts";
import options from "./fixture/options.ts"; import options from "./fixture/options.ts";
import { BUILD_ID } from "../src/server/build_id.ts"; import { BUILD_ID } from "../src/server/build_id.ts";
import { startFreshServer } from "./test_utils.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 ctx = await ServerContext.fromManifest(manifest, options);
const handler = ctx.handler(); const handler = ctx.handler();
@@ -815,6 +816,22 @@ Deno.test("PORT environment variable", {
serverProcess.kill("SIGTERM"); 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", { Deno.test("rendering custom _500.tsx page for default handlers", {
sanitizeOps: false, sanitizeOps: false,
sanitizeResources: false, sanitizeResources: false,
+2 -2
View File
@@ -3,13 +3,13 @@ import Header from "../components/Header.tsx";
import ComponentGallery from "../islands/ComponentGallery.tsx"; import ComponentGallery from "../islands/ComponentGallery.tsx";
import { asset, Head } from "$fresh/runtime.ts"; 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) { function getSource(path: string) {
return Deno.readTextFile(new URL(path, import.meta.url)); return Deno.readTextFile(new URL(path, import.meta.url));
} }
export const handler: MultiHandler<HomeProps> = { export const handler: Handlers<HomeProps> = {
async GET(req, ctx) { async GET(req, ctx) {
const props: HomeProps = { const props: HomeProps = {
sources: { sources: {
+2 -2
View File
@@ -1,5 +1,5 @@
import { asset, Head } from "$fresh/runtime.ts"; 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 { frontMatter, gfm } from "../../utils/markdown.ts";
import Header from "../../components/Header.tsx"; import Header from "../../components/Header.tsx";
@@ -21,7 +21,7 @@ interface Page extends TableOfContentsEntry {
data: Record<string, unknown>; data: Record<string, unknown>;
} }
export const handler: MultiHandler<Data> = { export const handler: Handlers<Data> = {
async GET(_req, ctx) { async GET(_req, ctx) {
const slug = ctx.params.slug; const slug = ctx.params.slug;
if (slug === "") { if (slug === "") {
+2 -2
View File
@@ -1,4 +1,4 @@
import { MultiHandler } from "$fresh/server.ts"; import { Handlers } from "$fresh/server.ts";
import { gfm } from "../utils/markdown.ts"; import { gfm } from "../utils/markdown.ts";
// TODO(lucacasonato): hash the file and use the hash as the filename, and serve // 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: () => { GET: () => {
return new Response(CSS, { return new Response(CSS, {
headers: { headers: {
+2 -2
View File
@@ -1,5 +1,5 @@
import { asset, Head } from "$fresh/runtime.ts"; 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 Counter from "../islands/Counter.tsx";
import LemonDrop from "../islands/LemonDrop.tsx"; import LemonDrop from "../islands/LemonDrop.tsx";
import Footer from "../components/Footer.tsx"; import Footer from "../components/Footer.tsx";
@@ -18,7 +18,7 @@ function isOpenGraphUA(header: string | null): boolean {
return header.startsWith("Twitterbot") || header.startsWith("Slackbot"); return header.startsWith("Twitterbot") || header.startsWith("Slackbot");
} }
export const handler: MultiHandler = { export const handler: Handlers = {
GET(req, ctx) { GET(req, ctx) {
const accept = req.headers.get("accept"); const accept = req.headers.get("accept");
const userAgent = req.headers.get("user-agent"); const userAgent = req.headers.get("user-agent");
+2 -2
View File
@@ -1,5 +1,5 @@
import { RouteConfig } from "$fresh/server.ts"; 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 { parse } from "$std/semver/mod.ts";
import VERSIONS from "../../versions.json" assert { type: "json" }; import VERSIONS from "../../versions.json" assert { type: "json" };
import { extname } from "$std/path/mod.ts"; import { extname } from "$std/path/mod.ts";
@@ -16,7 +16,7 @@ const contentTypes = new Map([
[".wasm", "application/wasm"], [".wasm", "application/wasm"],
]); ]);
export const handler: MultiHandler = { export const handler: Handlers = {
async GET(req, ctx) { async GET(req, ctx) {
const accept = req.headers.get("Accept"); const accept = req.headers.get("Accept");
const isHTML = accept?.includes("text/html"); const isHTML = accept?.includes("text/html");
+2 -2
View File
@@ -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" }; import VERSIONS from "../../versions.json" assert { type: "json" };
export const handler: MultiHandler = { export const handler: Handlers = {
GET(req) { GET(req) {
const accept = req.headers.get("accept"); const accept = req.headers.get("accept");
let path = "/docs/concepts/updating"; let path = "/docs/concepts/updating";