chore: simplify route creation logic (#1561)

This commit is contained in:
Marvin Hagemeister
2023-08-01 13:02:58 +02:00
committed by GitHub
parent 21c72abecc
commit e2c9e9a2b0
2 changed files with 29 additions and 57 deletions
+29 -56
View File
@@ -2,7 +2,6 @@ import {
dirname, dirname,
extname, extname,
fromFileUrl, fromFileUrl,
groupBy,
join, join,
JSONC, JSONC,
Status, Status,
@@ -26,12 +25,11 @@ import {
LayoutModule, LayoutModule,
LayoutRoute, LayoutRoute,
Middleware, Middleware,
MiddlewareHandler,
MiddlewareHandlerContext, MiddlewareHandlerContext,
MiddlewareModule, MiddlewareModule,
MiddlewareRoute, MiddlewareRoute,
Plugin, Plugin,
PluginMiddleware,
PluginRoute,
RenderFunction, RenderFunction,
RenderOptions, RenderOptions,
Route, Route,
@@ -189,8 +187,8 @@ export class ServerContext {
let errorModule: ErrorPageModule | null = null; let errorModule: ErrorPageModule | null = null;
const allRoutes = [ const allRoutes = [
...Object.entries(manifest.routes), ...Object.entries(manifest.routes),
...Object.entries(getMiddlewareRoutesFromPlugins(opts.plugins || [])), ...(opts.plugins ? getMiddlewareRoutesFromPlugins(opts.plugins) : []),
...Object.entries(getRoutesFromPlugins(opts.plugins || [])), ...(opts.plugins ? getRoutesFromPlugins(opts.plugins) : []),
]; ];
for ( for (
const [self, module] of allRoutes const [self, module] of allRoutes
@@ -1271,65 +1269,40 @@ async function readDenoConfig(
} }
function formatMiddlewarePath(path: string): string { function formatMiddlewarePath(path: string): string {
let formattedPath = path; const prefix = !path.startsWith("/") ? "/" : "";
if (!path.startsWith("/")) { const suffix = !path.endsWith("/") ? "/" : "";
formattedPath = `/${formattedPath}`; return prefix + path + suffix;
}
if (!formattedPath.endsWith("/")) {
formattedPath = `${formattedPath}/`;
}
return formattedPath;
} }
function getMiddlewareRoutesFromPlugins( function getMiddlewareRoutesFromPlugins(
plugins: Plugin[], plugins: Plugin[],
): Record<string, MiddlewareModule> { ): [string, MiddlewareModule][] {
// 1. Collect all middlewares from all plugins const middlewares = plugins.flatMap((plugin) => plugin.middlewares ?? []);
const allPluginMiddlewares = plugins.flatMap((plugin) =>
plugin.middlewares || []
);
// 2. Group PluginMiddleware by their path const mws: Record<
const groupedPluginMiddlewares: Record<string, PluginMiddleware[]> = { string,
...(groupBy( [string, { handler: MiddlewareHandler[] }]
allPluginMiddlewares, > = {};
(middleware) => for (let i = 0; i < middlewares.length; i++) {
`./routes${formatMiddlewarePath(middleware.path)}_middleware.ts`, const mw = middlewares[i];
) as Record<string, PluginMiddleware[]>), const handler = mw.middleware.handler;
}; const key = `./routes${formatMiddlewarePath(mw.path)}_middleware.ts`;
if (!mws[key]) mws[key] = [key, { handler: [] }];
mws[key][1].handler.push(...Array.isArray(handler) ? handler : [handler]);
}
// 3. Convert the grouped PluginMiddleware to MiddlewareModule return Object.values(mws);
// 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> { function getRoutesFromPlugins(plugins: Plugin[]): [string, RouteModule][] {
return (Object.assign( return plugins.flatMap((plugin) => plugin.routes ?? [])
{}, .map((route) => {
...[ return [`./routes${route.path}.ts`, {
...new Set( // deno-lint-ignore no-explicit-any
([] as PluginRoute[]).concat(...plugins.map((p) => p.routes || [])), default: route.component as any,
), handler: route.handler,
] }];
.map((route: PluginRoute) => ({ });
[`./routes${route.path}.ts`]: {
default: route.component,
handler: route.handler,
} as RouteModule,
})) || [],
));
} }
function sendResponse( function sendResponse(
-1
View File
@@ -25,4 +25,3 @@ export {
assertSpyCalls, assertSpyCalls,
spy, spy,
} from "https://deno.land/std@0.193.0/testing/mock.ts"; } 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";