feat: add ctx.redirect() helper (#2358)

This PR adds a `ctx.redirect(path, status)` helper that aims to reduce
the verbosity of having to manually create a `Response` obejct for a
mere redirect.

```ts
// Before
new Response(null, {
  status: 307,
  headers: {
    Location: "/foo/bar"
  },
})

// After
ctx.redirect("/foo/bar", 307)
```

If the second parameter is not passed, it will default to `302`.
This commit is contained in:
Marvin Hagemeister
2024-03-12 17:36:34 +01:00
committed by GitHub
parent 671751d572
commit e3508c3054
8 changed files with 82 additions and 20 deletions
+2
View File
@@ -65,6 +65,7 @@ import * as $not_found from "./routes/not_found.ts";
import * as $params from "./routes/params.tsx";
import * as $preact_boolean_attrs from "./routes/preact/boolean_attrs.tsx";
import * as $props_id_ from "./routes/props/[id].tsx";
import * as $redirect from "./routes/redirect.tsx";
import * as $route_groups_islands_index from "./routes/route-groups-islands/index.tsx";
import * as $route_groups_bar_baz_layout from "./routes/route-groups/(bar)/(baz)/_layout.tsx";
import * as $route_groups_bar_baz_baz from "./routes/route-groups/(bar)/(baz)/baz.tsx";
@@ -186,6 +187,7 @@ const manifest = {
"./routes/params.tsx": $params,
"./routes/preact/boolean_attrs.tsx": $preact_boolean_attrs,
"./routes/props/[id].tsx": $props_id_,
"./routes/redirect.tsx": $redirect,
"./routes/route-groups-islands/index.tsx": $route_groups_islands_index,
"./routes/route-groups/(bar)/(baz)/_layout.tsx":
$route_groups_bar_baz_layout,
+10
View File
@@ -0,0 +1,10 @@
import { FreshContext } from "$fresh/server.ts";
export const handler = {
GET(_req: Request, ctx: FreshContext) {
const rawStatus = ctx.url.searchParams.get("status");
const status = rawStatus !== null ? Number(rawStatus) : undefined;
const location = ctx.url.searchParams.get("path") ?? "/";
return ctx.redirect(location, status);
},
};