Skip to content

Commit ba8e1d8

Browse files
authored
docs: inline plugin example (denoland#2575)
Tackling - denoland#2546 Basically just inlined the old reference file and removed the islands and app builder to make it a bit more streamlined. Could make the example more dry but I'm not working from my normal dev environment.
1 parent 599efd7 commit ba8e1d8

File tree

1 file changed

+53
-2
lines changed

1 file changed

+53
-2
lines changed

docs/latest/concepts/plugins.md

Lines changed: 53 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -163,8 +163,59 @@ To create a middleware you need to create a `MiddlewareHandler` function.
163163

164164
And to create a route you can create both a Handler and/or component.
165165

166-
A very basic example can be found
167-
[here](https://github.com/denoland/fresh/blob/main/tests/fixture_plugin/utils/route-plugin.ts).
166+
Below is an example plugin that creates a route and middleware
167+
168+
```ts my-route-and-middleware-plugin.ts
169+
import { MiddlewareHandlerContext, Plugin } from "$fresh/server.ts";
170+
import { handler as testMiddleware } from "./sample_routes/_middleware.ts";
171+
import { SimpleRoute } from "./sample_routes/simple-route.tsx";
172+
export type { Options };
173+
174+
interface Options {
175+
title: string;
176+
}
177+
export type PluginMiddlewareState = {
178+
num: number;
179+
test: string;
180+
};
181+
182+
const twoPointlessMiddlewares = [
183+
async (
184+
_req: Request,
185+
ctx: MiddlewareHandlerContext<PluginMiddlewareState>,
186+
) => {
187+
ctx.state.num = ctx.state.num === undefined ? 1 : ctx.state.num + 1;
188+
return await ctx.next();
189+
},
190+
async (
191+
_req: Request,
192+
ctx: MiddlewareHandlerContext<PluginMiddlewareState>,
193+
) => {
194+
ctx.state.num = ctx.state.num === undefined ? 1 : ctx.state.num + 1;
195+
return await ctx.next();
196+
},
197+
];
198+
199+
export default function routePlugin(
200+
options: Options,
201+
): Plugin<PluginMiddlewareState> {
202+
return {
203+
name: "routePlugin",
204+
middlewares: [{
205+
middleware: { handler: testMiddleware },
206+
path: "/",
207+
}, {
208+
middleware: {
209+
handler: twoPointlessMiddlewares,
210+
},
211+
path: "lots-of-middleware",
212+
}],
213+
routes: [
214+
{ path: "no-leading-slash-here", component: SimpleRoute },
215+
],
216+
};
217+
}
218+
```
168219

169220
### Islands
170221

0 commit comments

Comments
 (0)