fix(server): Improve MiddlewareHandler type for plugins (#1534)

This commit is contained in:
Reed von Redwitz
2023-07-31 11:50:29 +02:00
committed by GitHub
parent 5fa6a67188
commit 1ad29e256b
4 changed files with 16 additions and 11 deletions
+4 -4
View File
@@ -325,7 +325,7 @@ export interface Island {
// --- PLUGINS --- // --- PLUGINS ---
export interface Plugin { export interface Plugin<State = Record<string, unknown>> {
/** The name of the plugin. Must be snake-case. */ /** The name of the plugin. Must be snake-case. */
name: string; name: string;
@@ -359,7 +359,7 @@ export interface Plugin {
routes?: PluginRoute[]; routes?: PluginRoute[];
middlewares?: PluginMiddleware[]; middlewares?: PluginMiddleware<State>[];
} }
export interface PluginRenderContext { export interface PluginRenderContext {
@@ -411,11 +411,11 @@ export interface PluginRenderFunctionResult {
requiresHydration: boolean; requiresHydration: boolean;
} }
export interface PluginMiddleware { export interface PluginMiddleware<State = Record<string, unknown>> {
/** A path in the format of a filename path without filetype */ /** A path in the format of a filename path without filetype */
path: string; path: string;
middleware: Middleware; middleware: Middleware<State>;
} }
export interface PluginRoute { export interface PluginRoute {
+5 -5
View File
@@ -1,14 +1,14 @@
import { Handlers, PageProps } from "../../../server.ts"; import { HandlerContext, Handlers, PageProps } from "../../../server.ts";
export const handler: Handlers = { export const handler: Handlers<unknown, { test: string }> = {
async GET(_req, ctx) { async GET(_req, ctx: HandlerContext<unknown, { test: string }>) {
const resp = await ctx.render(); const resp = await ctx.render();
return resp; return resp;
}, },
}; };
export default function Home(props: PageProps) { export default function Home(props: PageProps<unknown, { test: string }>) {
const value = props.state.test as string; const value = props.state.test;
return ( return (
<div> <div>
<h1>{value}</h1> <h1>{value}</h1>
+3 -1
View File
@@ -7,7 +7,9 @@ interface Options {
title: string; title: string;
} }
export default function routePlugin(options: Options): Plugin { export default function routePlugin(
options: Options,
): Plugin<{ test: string }> {
return { return {
name: "routePlugin", name: "routePlugin",
middlewares: [{ middlewares: [{
@@ -1,6 +1,9 @@
import { MiddlewareHandlerContext } from "$fresh/server.ts"; import { MiddlewareHandlerContext } from "$fresh/server.ts";
export async function handler(_req: Request, ctx: MiddlewareHandlerContext) { export async function handler(
_req: Request,
ctx: MiddlewareHandlerContext<{ test: string }>,
) {
ctx.state.test = "look, i'm set from a plugin!"; ctx.state.test = "look, i'm set from a plugin!";
const resp = await ctx.next(); const resp = await ctx.next();
return resp; return resp;