From 50db296fb72b833a1d8896f95106abfc5623a90a Mon Sep 17 00:00:00 2001 From: Reed von Redwitz Date: Thu, 13 Jul 2023 11:26:07 +0200 Subject: [PATCH] feat(server): plugins can add middlewares and routes (#1455) Co-authored-by: RoeHH Co-authored-by: Marvin Hagemeister --- docs/concepts/plugins.md | 19 +++++++- src/server/context.ts | 48 ++++++++++++++++++- src/server/types.ts | 21 ++++++++ tests/fixture_plugin/fresh.gen.ts | 6 ++- tests/fixture_plugin/options.ts | 2 + tests/fixture_plugin/routes/test.tsx | 17 +++++++ tests/fixture_plugin/utils/route-plugin.ts | 22 +++++++++ .../utils/sample_routes/AppBuilder.tsx | 18 +++++++ .../utils/sample_routes/_middleware.ts | 7 +++ tests/plugin_test.ts | 15 ++++++ 10 files changed, 171 insertions(+), 4 deletions(-) create mode 100644 tests/fixture_plugin/routes/test.tsx create mode 100644 tests/fixture_plugin/utils/route-plugin.ts create mode 100644 tests/fixture_plugin/utils/sample_routes/AppBuilder.tsx create mode 100644 tests/fixture_plugin/utils/sample_routes/_middleware.ts diff --git a/docs/concepts/plugins.md b/docs/concepts/plugins.md index d3064014..c86e3c07 100644 --- a/docs/concepts/plugins.md +++ b/docs/concepts/plugins.md @@ -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. diff --git a/src/server/context.ts b/src/server/context.ts index c07017fa..d85cabaa 100644 --- a/src/server/context.ts +++ b/src/server/context.ts @@ -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 { + 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 { + 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: { diff --git a/src/server/types.ts b/src/server/types.ts index d46adee7..f7d5ffc3 100644 --- a/src/server/types.ts +++ b/src/server/types.ts @@ -337,6 +337,10 @@ export interface Plugin { * propagate state between the render hook and the renderer. */ renderAsync?(ctx: PluginAsyncRenderContext): Promise; + + 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 | ComponentType; + + // deno-lint-ignore no-explicit-any + handler?: Handler | Handlers; +} diff --git a/tests/fixture_plugin/fresh.gen.ts b/tests/fixture_plugin/fresh.gen.ts index 39739cd6..8f644c5b 100644 --- a/tests/fixture_plugin/fresh.gen.ts +++ b/tests/fixture_plugin/fresh.gen.ts @@ -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, diff --git a/tests/fixture_plugin/options.ts b/tests/fixture_plugin/options.ts index 5555a284..511d546c 100644 --- a/tests/fixture_plugin/options.ts +++ b/tests/fixture_plugin/options.ts @@ -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; diff --git a/tests/fixture_plugin/routes/test.tsx b/tests/fixture_plugin/routes/test.tsx new file mode 100644 index 00000000..ca9d1d46 --- /dev/null +++ b/tests/fixture_plugin/routes/test.tsx @@ -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 ( +
+

{value}

+
+ ); +} diff --git a/tests/fixture_plugin/utils/route-plugin.ts b/tests/fixture_plugin/utils/route-plugin.ts new file mode 100644 index 00000000..a8c4de72 --- /dev/null +++ b/tests/fixture_plugin/utils/route-plugin.ts @@ -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), + }], + }; +} diff --git a/tests/fixture_plugin/utils/sample_routes/AppBuilder.tsx b/tests/fixture_plugin/utils/sample_routes/AppBuilder.tsx new file mode 100644 index 00000000..73f18c0c --- /dev/null +++ b/tests/fixture_plugin/utils/sample_routes/AppBuilder.tsx @@ -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 ( + <> + + {options.title} + +
+ +
+ + ); + }; +} diff --git a/tests/fixture_plugin/utils/sample_routes/_middleware.ts b/tests/fixture_plugin/utils/sample_routes/_middleware.ts new file mode 100644 index 00000000..cd7407fc --- /dev/null +++ b/tests/fixture_plugin/utils/sample_routes/_middleware.ts @@ -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; +} diff --git a/tests/plugin_test.ts b/tests/plugin_test.ts index 3f91ef6e..8bb225a9 100644 --- a/tests/plugin_test.ts +++ b/tests/plugin_test.ts @@ -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, + `

look, i'm set from a plugin!

`, + ); + assertStringIncludes( + body, + `Title Set From Plugin Config`, + ); +}); + Deno.test({ name: "/with-island hydration", async fn(t) {