feat: pass middleware state in props (#1264)
This commit is contained in:
@@ -7,15 +7,18 @@ An application wrapper is defined in an `_app.tsx` file in `routes/` folder. It
|
|||||||
must contain a default export that is a regular Preact component. Only one such
|
must contain a default export that is a regular Preact component. Only one such
|
||||||
wrapper is allowed per application.
|
wrapper is allowed per application.
|
||||||
|
|
||||||
It receives component through props which is to be wrapped. For instance, it
|
The component to be wrapped is received via props, in addition to a few other
|
||||||
allows to introduce a global container for the whole application.
|
things. This allows for the introduction of a global container functioning as a
|
||||||
|
template which can be conditioned based on state and params. Note that any state
|
||||||
|
set by middleware is available via `props.state`.
|
||||||
|
|
||||||
```tsx
|
```tsx
|
||||||
// routes/_app.tsx
|
// routes/_app.tsx
|
||||||
|
|
||||||
import { AppProps } from "$fresh/server.ts";
|
import { AppProps } from "$fresh/server.ts";
|
||||||
|
|
||||||
export default function App({ Component }: AppProps) {
|
export default function App({ Component, state }: AppProps) {
|
||||||
|
//do something with state here
|
||||||
return (
|
return (
|
||||||
<div class="wrapper">
|
<div class="wrapper">
|
||||||
<Component />
|
<Component />
|
||||||
|
|||||||
@@ -10,7 +10,10 @@ use-cases for this are logging, authentication, and performance monitoring.
|
|||||||
|
|
||||||
Each middleware gets passed a `next` function in the context argument that is
|
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.
|
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
|
||||||
|
[routes](/docs/concepts/routes.md).
|
||||||
|
|
||||||
```ts
|
```ts
|
||||||
// routes/_middleware.ts
|
// routes/_middleware.ts
|
||||||
|
|||||||
@@ -17,8 +17,9 @@ passed a `render` function that it can call to invoke rendering a component.
|
|||||||
The component is the template for a page. It is a JSX element that is rendered
|
The component is the template for a page. It is a JSX element that is rendered
|
||||||
on the server. The page component gets passed props that can be used by it to
|
on the server. The page component gets passed props that can be used by it to
|
||||||
determine exactly what should be rendered. By default components receives props
|
determine exactly what should be rendered. By default components receives props
|
||||||
consisting of: the request URL, the matches from the URL pattern match, and any
|
consisting of: the request URL, the matching route (as a string), the matches
|
||||||
data passed to the handler's `render` function.
|
from the URL pattern match, any state set by middleware, and any data passed to
|
||||||
|
the handler's `render` function.
|
||||||
|
|
||||||
## Handler route
|
## Handler route
|
||||||
|
|
||||||
|
|||||||
@@ -22,7 +22,7 @@ Route files that render HTML are JavaScript or TypeScript modules that export a
|
|||||||
JSX component as their default export. This component will be rendered for every
|
JSX component as their default export. This component will be rendered for every
|
||||||
request to the route's path. The component receives a few properties that can be
|
request to the route's path. The component receives a few properties that can be
|
||||||
used to customize the rendered output, such as the current route, the url of the
|
used to customize the rendered output, such as the current route, the url of the
|
||||||
request, and handler data (more on that later).
|
request, state set by middleware, and handler data (more on the last two later).
|
||||||
|
|
||||||
In the demo project we'll create a route to handle the `/about` page. To do
|
In the demo project we'll create a route to handle the `/about` page. To do
|
||||||
this, one needs to create a new `routes/about.tsx` file. In this file, we can
|
this, one needs to create a new `routes/about.tsx` file. In this file, we can
|
||||||
|
|||||||
@@ -571,6 +571,7 @@ export class ServerContext {
|
|||||||
return (
|
return (
|
||||||
req: Request,
|
req: Request,
|
||||||
params: Record<string, string>,
|
params: Record<string, string>,
|
||||||
|
state?: Record<string, unknown>,
|
||||||
error?: unknown,
|
error?: unknown,
|
||||||
) => {
|
) => {
|
||||||
return async (data?: Data, options?: RenderOptions) => {
|
return async (data?: Data, options?: RenderOptions) => {
|
||||||
@@ -601,6 +602,7 @@ export class ServerContext {
|
|||||||
url: new URL(req.url),
|
url: new URL(req.url),
|
||||||
params,
|
params,
|
||||||
data,
|
data,
|
||||||
|
state,
|
||||||
error,
|
error,
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -647,8 +649,8 @@ export class ServerContext {
|
|||||||
(route.handler as Handler)(req, {
|
(route.handler as Handler)(req, {
|
||||||
...ctx,
|
...ctx,
|
||||||
params,
|
params,
|
||||||
render: createRender(req, params),
|
render: createRender(req, params, ctx.state),
|
||||||
renderNotFound: createUnknownRender(req, {}),
|
renderNotFound: createUnknownRender(req, params, ctx.state),
|
||||||
}),
|
}),
|
||||||
};
|
};
|
||||||
} else {
|
} else {
|
||||||
@@ -662,8 +664,8 @@ export class ServerContext {
|
|||||||
handler(req, {
|
handler(req, {
|
||||||
...ctx,
|
...ctx,
|
||||||
params,
|
params,
|
||||||
render: createRender(req, params),
|
render: createRender(req, params, ctx.state),
|
||||||
renderNotFound: createUnknownRender(req, {}),
|
renderNotFound: createUnknownRender(req, params, ctx.state),
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -700,7 +702,7 @@ export class ServerContext {
|
|||||||
{
|
{
|
||||||
...ctx,
|
...ctx,
|
||||||
error,
|
error,
|
||||||
render: errorHandlerRender(req, {}, error),
|
render: errorHandlerRender(req, {}, undefined, error),
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -50,6 +50,7 @@ export interface RenderOptions<Data> {
|
|||||||
params: Record<string, string | string[]>;
|
params: Record<string, string | string[]>;
|
||||||
renderFn: RenderFunction;
|
renderFn: RenderFunction;
|
||||||
data?: Data;
|
data?: Data;
|
||||||
|
state?: Record<string, unknown>;
|
||||||
error?: unknown;
|
error?: unknown;
|
||||||
lang?: string;
|
lang?: string;
|
||||||
}
|
}
|
||||||
@@ -134,6 +135,7 @@ export async function render<Data>(
|
|||||||
url: opts.url,
|
url: opts.url,
|
||||||
route: opts.route.pattern,
|
route: opts.route.pattern,
|
||||||
data: opts.data,
|
data: opts.data,
|
||||||
|
state: opts.state,
|
||||||
};
|
};
|
||||||
if (opts.error) {
|
if (opts.error) {
|
||||||
props.error = opts.error;
|
props.error = opts.error;
|
||||||
@@ -153,6 +155,7 @@ export async function render<Data>(
|
|||||||
url: opts.url,
|
url: opts.url,
|
||||||
route: opts.route.pattern,
|
route: opts.route.pattern,
|
||||||
data: opts.data,
|
data: opts.data,
|
||||||
|
state: opts.state!,
|
||||||
Component() {
|
Component() {
|
||||||
return h(opts.route.component! as ComponentType<unknown>, props);
|
return h(opts.route.component! as ComponentType<unknown>, props);
|
||||||
},
|
},
|
||||||
|
|||||||
+2
-1
@@ -38,7 +38,7 @@ export type RenderFunction = (
|
|||||||
/// --- ROUTES ---
|
/// --- ROUTES ---
|
||||||
|
|
||||||
// deno-lint-ignore no-explicit-any
|
// deno-lint-ignore no-explicit-any
|
||||||
export interface PageProps<T = any> {
|
export interface PageProps<T = any, S = Record<string, unknown>> {
|
||||||
/** The URL of the request that resulted in this page being rendered. */
|
/** The URL of the request that resulted in this page being rendered. */
|
||||||
url: URL;
|
url: URL;
|
||||||
|
|
||||||
@@ -61,6 +61,7 @@ export interface PageProps<T = any> {
|
|||||||
* `undefined`.
|
* `undefined`.
|
||||||
*/
|
*/
|
||||||
data: T;
|
data: T;
|
||||||
|
state: S;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface RouteConfig {
|
export interface RouteConfig {
|
||||||
|
|||||||
@@ -32,9 +32,11 @@ import * as $26 from "./routes/middleware_root.ts";
|
|||||||
import * as $27 from "./routes/not_found.ts";
|
import * as $27 from "./routes/not_found.ts";
|
||||||
import * as $28 from "./routes/params.tsx";
|
import * as $28 from "./routes/params.tsx";
|
||||||
import * as $29 from "./routes/props/[id].tsx";
|
import * as $29 from "./routes/props/[id].tsx";
|
||||||
import * as $30 from "./routes/static.tsx";
|
import * as $30 from "./routes/state-in-props/_middleware.ts";
|
||||||
import * as $31 from "./routes/status_overwrite.tsx";
|
import * as $31 from "./routes/state-in-props/index.tsx";
|
||||||
import * as $32 from "./routes/wildcard.tsx";
|
import * as $32 from "./routes/static.tsx";
|
||||||
|
import * as $33 from "./routes/status_overwrite.tsx";
|
||||||
|
import * as $34 from "./routes/wildcard.tsx";
|
||||||
import * as $$0 from "./islands/Counter.tsx";
|
import * as $$0 from "./islands/Counter.tsx";
|
||||||
import * as $$1 from "./islands/ReturningNull.tsx";
|
import * as $$1 from "./islands/ReturningNull.tsx";
|
||||||
import * as $$2 from "./islands/RootFragment.tsx";
|
import * as $$2 from "./islands/RootFragment.tsx";
|
||||||
@@ -75,9 +77,11 @@ const manifest = {
|
|||||||
"./routes/not_found.ts": $27,
|
"./routes/not_found.ts": $27,
|
||||||
"./routes/params.tsx": $28,
|
"./routes/params.tsx": $28,
|
||||||
"./routes/props/[id].tsx": $29,
|
"./routes/props/[id].tsx": $29,
|
||||||
"./routes/static.tsx": $30,
|
"./routes/state-in-props/_middleware.ts": $30,
|
||||||
"./routes/status_overwrite.tsx": $31,
|
"./routes/state-in-props/index.tsx": $31,
|
||||||
"./routes/wildcard.tsx": $32,
|
"./routes/static.tsx": $32,
|
||||||
|
"./routes/status_overwrite.tsx": $33,
|
||||||
|
"./routes/wildcard.tsx": $34,
|
||||||
},
|
},
|
||||||
islands: {
|
islands: {
|
||||||
"./islands/Counter.tsx": $$0,
|
"./islands/Counter.tsx": $$0,
|
||||||
|
|||||||
@@ -2,10 +2,16 @@ import { Head } from "$fresh/runtime.ts";
|
|||||||
import { AppProps } from "$fresh/server.ts";
|
import { AppProps } from "$fresh/server.ts";
|
||||||
|
|
||||||
export default function App(props: AppProps) {
|
export default function App(props: AppProps) {
|
||||||
|
const statefulValue = props.state?.root === "root_mw"
|
||||||
|
? "The freshest framework!"
|
||||||
|
: "";
|
||||||
|
const specialCase = props.state?.stateInProps as string;
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<Head>
|
<Head>
|
||||||
<meta name="description" content="Hello world!" />
|
<meta name="description" content="Hello world!" />
|
||||||
|
<meta name="generator" content={statefulValue} />
|
||||||
|
{specialCase && <meta name="specialTag" content={specialCase} />}
|
||||||
</Head>
|
</Head>
|
||||||
<props.Component />
|
<props.Component />
|
||||||
</>
|
</>
|
||||||
|
|||||||
@@ -0,0 +1,10 @@
|
|||||||
|
import { MiddlewareHandlerContext } from "$fresh/server.ts";
|
||||||
|
|
||||||
|
export async function handler(
|
||||||
|
_req: Request,
|
||||||
|
ctx: MiddlewareHandlerContext,
|
||||||
|
) {
|
||||||
|
ctx.state.stateInProps = "look, i am set from middleware";
|
||||||
|
const resp = await ctx.next();
|
||||||
|
return resp;
|
||||||
|
}
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
import { Handlers, PageProps } from "$fresh/server.ts";
|
||||||
|
|
||||||
|
export const handler: Handlers<boolean> = {
|
||||||
|
GET(_, ctx) {
|
||||||
|
const complexValue = true;
|
||||||
|
return ctx.render(complexValue);
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
export default function Page(props: PageProps<boolean>) {
|
||||||
|
let valueFromState = props.state.stateInProps as string;
|
||||||
|
if (props.data) {
|
||||||
|
valueFromState = valueFromState.toUpperCase();
|
||||||
|
}
|
||||||
|
return (
|
||||||
|
<div>
|
||||||
|
<h1>{valueFromState}</h1>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
+33
-1
@@ -30,6 +30,14 @@ Deno.test("/ page prerender", async () => {
|
|||||||
body,
|
body,
|
||||||
'<meta name="description" content="Hello world!"/>',
|
'<meta name="description" content="Hello world!"/>',
|
||||||
);
|
);
|
||||||
|
assertStringIncludes(
|
||||||
|
body,
|
||||||
|
'<meta name="generator" content="The freshest framework!"/>',
|
||||||
|
);
|
||||||
|
assert(
|
||||||
|
!body.includes("specialTag"),
|
||||||
|
`Expected actual: "${body}" to not contain: "specialTag"`,
|
||||||
|
);
|
||||||
assertStringIncludes(body, `<link rel="modulepreload"`);
|
assertStringIncludes(body, `<link rel="modulepreload"`);
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -41,7 +49,7 @@ Deno.test("/props/123 page prerender", async () => {
|
|||||||
const body = await resp.text();
|
const body = await resp.text();
|
||||||
assertStringIncludes(
|
assertStringIncludes(
|
||||||
body,
|
body,
|
||||||
`{"params":{"id":"123"},"url":"https://fresh.deno.dev/props/123","route":"/props/:id"}`,
|
`{"params":{"id":"123"},"url":"https://fresh.deno.dev/props/123","route":"/props/:id","state":{"root":"root_mw"}}`,
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -419,6 +427,22 @@ Deno.test("/connInfo", async () => {
|
|||||||
assertEquals(body, "localhost");
|
assertEquals(body, "localhost");
|
||||||
});
|
});
|
||||||
|
|
||||||
|
Deno.test("state in page props", async () => {
|
||||||
|
const resp = await handler(
|
||||||
|
new Request("https://fresh.deno.dev/state-in-props"),
|
||||||
|
);
|
||||||
|
assert(resp);
|
||||||
|
assertEquals(resp.status, Status.OK);
|
||||||
|
assertEquals(resp.headers.get("content-type"), "text/html; charset=utf-8");
|
||||||
|
const body = await resp.text();
|
||||||
|
assertStringIncludes(
|
||||||
|
body,
|
||||||
|
'<meta name="generator" content="The freshest framework!"/>',
|
||||||
|
);
|
||||||
|
assertStringIncludes(body, "specialTag");
|
||||||
|
assertStringIncludes(body, "LOOK, I AM SET FROM MIDDLEWARE");
|
||||||
|
});
|
||||||
|
|
||||||
Deno.test({
|
Deno.test({
|
||||||
name: "/middleware - root",
|
name: "/middleware - root",
|
||||||
fn: async () => {
|
fn: async () => {
|
||||||
@@ -621,6 +645,14 @@ Deno.test("experimental Deno.serve", {
|
|||||||
body,
|
body,
|
||||||
'<meta name="description" content="Hello world!"/>',
|
'<meta name="description" content="Hello world!"/>',
|
||||||
);
|
);
|
||||||
|
assertStringIncludes(
|
||||||
|
body,
|
||||||
|
'<meta name="generator" content="The freshest framework!"/>',
|
||||||
|
);
|
||||||
|
assert(
|
||||||
|
!body.includes("specialTag"),
|
||||||
|
`Expected actual: "${body}" to not contain: "specialTag"`,
|
||||||
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
await t.step("static file", async () => {
|
await t.step("static file", async () => {
|
||||||
|
|||||||
Reference in New Issue
Block a user