diff --git a/docs/latest/concepts/data-fetching.md b/docs/latest/concepts/data-fetching.md index 2ddc4abc..6ebf243e 100644 --- a/docs/latest/concepts/data-fetching.md +++ b/docs/latest/concepts/data-fetching.md @@ -20,7 +20,9 @@ export const handler: Handlers = { async GET(_req, ctx) { const project = await db.projects.findOne({ id: ctx.params.id }); if (!project) { - return new Response("Project not found", { status: 404 }); + return ctx.renderNotFound({ + message: "Project does not exist", + }); } return ctx.render(project); }, @@ -40,3 +42,34 @@ The type parameter on the `PageProps`, `Handlers`, `Handler`, and `FreshContext` 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. + +## Asynchronous routes + +As a shortcut for combining a `GET` handler with a route, you can define your +route as `async`. An `async` route (a route that returns a promise) will be +called with the `Request` and a `RouteContext` (similar to a `HandlerContext`). +Here is the above example rewritten using this shortcut: + +```tsx routes/projects/[id].tsx +interface Project { + name: string; + stars: number; +} + +export default async function ProjectPage(_req, ctx: FreshContext) { + const project: Project | null = await db.projects.findOne({ + id: ctx.params.id, + }); + + if (!project) { + return

Project not found

; + } + + return ( +
+

{project.name}

+

{project.stars} stars

+
+ ); +} +``` diff --git a/docs/latest/getting-started/custom-handlers.md b/docs/latest/getting-started/custom-handlers.md index e0255505..d20cd1ee 100644 --- a/docs/latest/getting-started/custom-handlers.md +++ b/docs/latest/getting-started/custom-handlers.md @@ -64,3 +64,7 @@ export const handler: Handlers = { }, }; ``` + +Handlers can do much more, including fetching data from a database or external +API and passing it to their route. See [Data fetching](/docs/concepts/) for more +details. diff --git a/docs/latest/getting-started/fetching-data.md b/docs/latest/getting-started/fetching-data.md deleted file mode 100644 index 998c591e..00000000 --- a/docs/latest/getting-started/fetching-data.md +++ /dev/null @@ -1,55 +0,0 @@ ---- -description: | - Fetch data for routes dynamically by creating a custom handler and passing - data to the render function. ---- - -All of the pages in the demo project so far have not used any dynamic data -during rendering. In real projects, this is often different. In many cases you -may need to read a file from disk (e.g. markdown for a blog post), or fetch some -user data from an API or database. - -In order to fetch data, the route component must be asynchronous. The first -parameter contains the client's -[`Request`](https://developer.mozilla.org/en-US/docs/Web/API/Request) object. -The second `ctx` parameter is used to get the route parameters. - -Here is an example of a route that fetches user data from the GitHub API and -renders it in a page component. - -```tsx routes/github/[username].tsx -import { RouteContext } from "$fresh/server.ts"; - -interface GitHubResponse { - login: string; - name: string; - avatar_url: string; -} - -export default async function Page(_req: Request, ctx: RouteContext) { - const resp = await fetch( - `https://api.github.com/users/${ctx.params.username}`, - ); - - if (!resp.ok) { - return

An Error occurred

; - } - - const { login, name, avatar_url } = (await resp.json()) as GitHubResponse; - - return ( -
- -

{name}

-

{login}

-
- ); -} -``` - -The data is first fetched inside our page component. We check that the response -is returned successfully, by checking whether the -[`ok`](https://developer.mozilla.org/en-US/docs/Web/API/Response/ok) property is -true. If the API call was successful, we will see our div with the user's GitHub -image, name, and username. Otherwise, we should see a heading saying: "An Error -occurred." diff --git a/docs/toc.ts b/docs/toc.ts index e25cc233..b143f012 100644 --- a/docs/toc.ts +++ b/docs/toc.ts @@ -34,7 +34,6 @@ const toc: RawTableOfContents = { ["create-a-route", "Create a route", "link:latest"], ["dynamic-routes", "Dynamic routes", "link:latest"], ["custom-handlers", "Custom handlers", "link:latest"], - ["fetching-data", "Fetching data", "link:latest"], ["form-submissions", "Form submissions", "link:latest"], ["adding-interactivity", "Adding interactivity", "link:latest"], ["deploy-to-production", "Deploy to production", "link:latest"], @@ -116,7 +115,6 @@ const toc: RawTableOfContents = { ["create-a-route", "Create a route"], ["dynamic-routes", "Dynamic routes"], ["custom-handlers", "Custom handlers"], - ["fetching-data", "Fetching data"], ["form-submissions", "Form submissions"], ["adding-interactivity", "Adding interactivity"], ["deploy-to-production", "Deploy to production"], diff --git a/www/fresh.gen.ts b/www/fresh.gen.ts index 8489f262..3210600d 100644 --- a/www/fresh.gen.ts +++ b/www/fresh.gen.ts @@ -8,6 +8,7 @@ import * as $_app from "./routes/_app.tsx"; import * as $_middleware from "./routes/_middleware.ts"; import * as $components from "./routes/components.tsx"; import * as $docs_slug_ from "./routes/docs/[...slug].tsx"; +import * as $docs_middleware from "./routes/docs/_middleware.ts"; import * as $docs_index from "./routes/docs/index.tsx"; import * as $index from "./routes/index.tsx"; import * as $raw from "./routes/raw.ts"; @@ -30,6 +31,7 @@ const manifest = { "./routes/_middleware.ts": $_middleware, "./routes/components.tsx": $components, "./routes/docs/[...slug].tsx": $docs_slug_, + "./routes/docs/_middleware.ts": $docs_middleware, "./routes/docs/index.tsx": $docs_index, "./routes/index.tsx": $index, "./routes/raw.ts": $raw, diff --git a/www/routes/docs/_middleware.ts b/www/routes/docs/_middleware.ts new file mode 100644 index 00000000..ecbca4b1 --- /dev/null +++ b/www/routes/docs/_middleware.ts @@ -0,0 +1,23 @@ +import { FreshContext } from "$fresh/server.ts"; + +const REDIRECTS: Record = { + "/docs/getting-started/fetching-data": + "/docs/getting-started/custom-handlers", +}; + +export async function handler( + _req: Request, + ctx: FreshContext, +) { + // Redirect from old doc URLs to new ones + const redirect = REDIRECTS[ctx.url.pathname]; + if (redirect) { + const url = new URL(redirect, ctx.url.origin); + return new Response("", { + status: 307, + headers: { location: url.href }, + }); + } + + return await ctx.next(); +}