fix(server): merge competing PluginMiddleware handlers together (#1545)

This commit is contained in:
Reed von Redwitz
2023-07-31 13:56:38 +00:00
committed by GitHub
parent 80fece0d3c
commit 21c72abecc
9 changed files with 149 additions and 24 deletions
+41 -15
View File
@@ -2,6 +2,7 @@ import {
dirname,
extname,
fromFileUrl,
groupBy,
join,
JSONC,
Status,
@@ -1269,24 +1270,49 @@ async function readDenoConfig(
}
}
function formatMiddlewarePath(path: string): string {
let formattedPath = path;
if (!path.startsWith("/")) {
formattedPath = `/${formattedPath}`;
}
if (!formattedPath.endsWith("/")) {
formattedPath = `${formattedPath}/`;
}
return formattedPath;
}
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,
},
})) || [],
));
// 1. Collect all middlewares from all plugins
const allPluginMiddlewares = plugins.flatMap((plugin) =>
plugin.middlewares || []
);
// 2. Group PluginMiddleware by their path
const groupedPluginMiddlewares: Record<string, PluginMiddleware[]> = {
...(groupBy(
allPluginMiddlewares,
(middleware) =>
`./routes${formatMiddlewarePath(middleware.path)}_middleware.ts`,
) as Record<string, PluginMiddleware[]>),
};
// 3. Convert the grouped PluginMiddleware to MiddlewareModule
// this involves merging the Handler or Handler[]
const middlewareRoutes: Record<string, MiddlewareModule> = Object.fromEntries(
Object.entries(groupedPluginMiddlewares).map(([key, pluginMiddlewares]) => {
const handler = pluginMiddlewares.flatMap((pluginMiddleware) => {
const middlewareHandler = pluginMiddleware.middleware.handler;
return Array.isArray(middlewareHandler)
? middlewareHandler
: [middlewareHandler];
});
return [key, { handler }];
}),
);
return middlewareRoutes;
}
function getRoutesFromPlugins(plugins: Plugin[]): Record<string, RouteModule> {
+1
View File
@@ -25,3 +25,4 @@ export {
assertSpyCalls,
spy,
} from "https://deno.land/std@0.193.0/testing/mock.ts";
export { groupBy } from "https://deno.land/std@0.193.0/collections/group_by.ts";