feat(server): plugins can add middlewares and routes (#1455)

Co-authored-by: RoeHH <git@roeh.ch>
Co-authored-by: Marvin Hagemeister <marvin@deno.com>
This commit is contained in:
Reed von Redwitz
2023-07-13 11:26:07 +02:00
committed by GitHub
co-authored by RoeHH Marvin Hagemeister
parent 7dee138bee
commit 50db296fb7
10 changed files with 171 additions and 4 deletions
+18 -1
View File
@@ -52,7 +52,8 @@ const plugin: Plugin = {
```
A plugin containing only a name is technically valid, but not very useful. To be
able to do anything with a plugin, it must register some hooks.
able to do anything with a plugin, it must register some hooks, middlewares, or
routes.
### Hook: `render`
@@ -123,3 +124,19 @@ all rendering is complete -- they wrap around the underlying JSX->string
rendering, plugin `render` hooks, and the
[`RenderFunction`](https://deno.land/x/fresh/server.ts?s=RenderFunction) that
may be provided to Fresh's `start` entrypoint in the `main.ts` file.
### Routes and Middlewares
You can create routes and middlewares that get loaded and rendered like the
normal [routes](/docs/concepts/routes) and
[middlewares](/docs/concepts/middleware).
The plugin routes and middlewares need a defined path in the format of a file
name without a filetype inside the routes directory(E.g. `blog/index`,
`blog/[slug]`).
For more examples see the [Concepts: Routing](/docs/concepts/routing) page.
To create a middleware you need to create a `MiddlewareHandler` function.
And to create a route you can create both a Handler and/or component.
+47 -1
View File
@@ -27,6 +27,8 @@ import {
MiddlewareModule,
MiddlewareRoute,
Plugin,
PluginMiddleware,
PluginRoute,
RenderFunction,
RenderOptions,
Route,
@@ -176,7 +178,14 @@ export class ServerContext {
let app: AppModule = DEFAULT_APP;
let notFound: UnknownPage = DEFAULT_NOT_FOUND;
let error: ErrorPage = DEFAULT_ERROR;
for (const [self, module] of Object.entries(manifest.routes)) {
const allRoutes = [
...Object.entries(manifest.routes),
...Object.entries(getMiddlewareRoutesFromPlugins(opts.plugins || [])),
...Object.entries(getRoutesFromPlugins(opts.plugins || [])),
];
for (
const [self, module] of allRoutes
) {
const url = new URL(self, baseUrl).href;
if (!url.startsWith(baseUrl + "routes")) {
throw new TypeError("Page is not a child of the basepath.");
@@ -1133,6 +1142,43 @@ async function readDenoConfig(
}
}
function getMiddlewareRoutesFromPlugins(
plugins: Plugin[],
): Record<string, MiddlewareModule> {
return (Object.assign(
{},
...[
...new Set(
([] as PluginMiddleware[]).concat(
...plugins.map((p) => p.middlewares || []),
),
),
]
.map((middleware: PluginMiddleware) => ({
[`./routes${middleware.path}_middleware.ts`]: {
handler: middleware.middleware.handler,
},
})) || [],
));
}
function getRoutesFromPlugins(plugins: Plugin[]): Record<string, RouteModule> {
return (Object.assign(
{},
...[
...new Set(
([] as PluginRoute[]).concat(...plugins.map((p) => p.routes || [])),
),
]
.map((route: PluginRoute) => ({
[`./routes${route.path}.ts`]: {
default: route.component,
handler: route.handler,
} as RouteModule,
})) || [],
));
}
function sendResponse(
resp: [string, ContentSecurityPolicy | undefined],
options: {
+21
View File
@@ -337,6 +337,10 @@ export interface Plugin {
* propagate state between the render hook and the renderer.
*/
renderAsync?(ctx: PluginAsyncRenderContext): Promise<PluginRenderResult>;
routes?: PluginRoute[];
middlewares?: PluginMiddleware[];
}
export interface PluginRenderContext {
@@ -387,3 +391,20 @@ export interface PluginRenderFunctionResult {
* client. */
requiresHydration: boolean;
}
export interface PluginMiddleware {
/** A path in the format of a filename path without filetype */
path: string;
middleware: Middleware;
}
export interface PluginRoute {
/** A path in the format of a filename path without filetype */
path: string;
component?: ComponentType<PageProps> | ComponentType<AppProps>;
// deno-lint-ignore no-explicit-any
handler?: Handler<any, any> | Handlers<any, any>;
}
+4 -2
View File
@@ -3,13 +3,15 @@
// This file is automatically updated during development when running `dev.ts`.
import * as $0 from "./routes/static.tsx";
import * as $1 from "./routes/with-island.tsx";
import * as $1 from "./routes/test.tsx";
import * as $2 from "./routes/with-island.tsx";
import * as $$0 from "./islands/Island.tsx";
const manifest = {
routes: {
"./routes/static.tsx": $0,
"./routes/with-island.tsx": $1,
"./routes/test.tsx": $1,
"./routes/with-island.tsx": $2,
},
islands: {
"./islands/Island.tsx": $$0,
+2
View File
@@ -2,11 +2,13 @@ import { FreshOptions } from "$fresh/server.ts";
import cssInjectPlugin from "./utils/css-inject-plugin.ts";
import jsInjectPlugin from "./utils/js-inject-plugin.ts";
import cssInjectPluginAsync from "./utils/css-inject-plugin-async.ts";
import routePlugin from "./utils/route-plugin.ts";
export default {
plugins: [
cssInjectPlugin,
jsInjectPlugin,
cssInjectPluginAsync,
routePlugin({ title: "Title Set From Plugin Config" }),
],
} as FreshOptions;
+17
View File
@@ -0,0 +1,17 @@
import { Handlers, PageProps } from "../../../server.ts";
export const handler: Handlers = {
async GET(_req, ctx) {
const resp = await ctx.render();
return resp;
},
};
export default function Home(props: PageProps) {
const value = props.state.test as string;
return (
<div>
<h1>{value}</h1>
</div>
);
}
@@ -0,0 +1,22 @@
import { Plugin } from "$fresh/server.ts";
import { handler as testMiddleware } from "./sample_routes/_middleware.ts";
import { AppBuilder } from "./sample_routes/AppBuilder.tsx";
export type { Options };
interface Options {
title: string;
}
export default function routePlugin(options: Options): Plugin {
return {
name: "routePlugin",
middlewares: [{
middleware: { handler: testMiddleware },
path: "/",
}],
routes: [{
path: "/_app",
component: AppBuilder(options),
}],
};
}
@@ -0,0 +1,18 @@
import { AppProps } from "$fresh/server.ts";
import { Head } from "../../../../runtime.ts";
import { Options } from "../route-plugin.ts";
export function AppBuilder(options: Options) {
return ({ Component }: AppProps) => {
return (
<>
<Head>
<title>{options.title}</title>
</Head>
<main class="max-w-screen-md px-4 pt-16 mx-auto">
<Component />
</main>
</>
);
};
}
@@ -0,0 +1,7 @@
import { MiddlewareHandlerContext } from "$fresh/server.ts";
export async function handler(_req: Request, ctx: MiddlewareHandlerContext) {
ctx.state.test = "look, i'm set from a plugin!";
const resp = await ctx.next();
return resp;
}
+15
View File
@@ -53,6 +53,21 @@ Deno.test("/with-island prerender", async () => {
);
});
Deno.test("plugin routes and middleware", async () => {
const resp = await router(new Request("https://fresh.deno.dev/test"));
assert(resp);
assertEquals(resp.status, Status.OK);
const body = await resp.text();
assertStringIncludes(
body,
`<h1>look, i'm set from a plugin!</h1>`,
);
assertStringIncludes(
body,
`<title>Title Set From Plugin Config</title>`,
);
});
Deno.test({
name: "/with-island hydration",
async fn(t) {