Optimiere Middleware-Verarbeitung in Flummpress und Router, verbessere Typen für Middleware

This commit is contained in:
Flummi 2025-03-15 21:28:13 +01:00
parent 31230f272f
commit 57f8c5d18c
2 changed files with 8 additions and 10 deletions

View File

@ -72,11 +72,9 @@ export default class Flummpress {
const handler = methods[method!]; const handler = methods[method!];
const middleware = methods[`${method}mw`]; const middleware = methods[`${method}mw`];
if(middleware) {
for(const mw of middleware) { for(const mw of middleware) {
await mw(req, res, () => {}); await mw(req, res, () => {});
} }
}
if(handler) { if(handler) {
req.params = req.parsedUrl.pathname.match(new RegExp(pathPattern))?.groups || {}; req.params = req.parsedUrl.pathname.match(new RegExp(pathPattern))?.groups || {};

View File

@ -2,9 +2,7 @@ import fs from "node:fs";
import path from "node:path"; import path from "node:path";
import Tpl from "./template.js"; import Tpl from "./template.js";
import { RouteCallback } from "./types.js"; import { Middleware, RouteCallback } from "./types.js";
export default class Router { export default class Router {
private routes: Map<RegExp | string, { [key: string]: RouteCallback | RouteCallback[] }>; private routes: Map<RegExp | string, { [key: string]: RouteCallback | RouteCallback[] }>;
@ -166,9 +164,11 @@ export default class Router {
path: string | RegExp, path: string | RegExp,
cb: RouteCallback, cb: RouteCallback,
method: string, method: string,
middleware: RouteCallback | RouteCallback[] = [] middleware: Middleware | Middleware[] = []
): this { ): this {
const middlewareArray = Array.isArray(middleware) ? middleware : [middleware]; if(!Array.isArray(middleware)) {
middleware = [ middleware ];
}
if(!this.routes.has(path)) { if(!this.routes.has(path)) {
this.routes.set(path, {}); this.routes.set(path, {});
@ -177,7 +177,7 @@ export default class Router {
this.routes.set(path, { this.routes.set(path, {
...this.routes.get(path), ...this.routes.get(path),
[method]: cb, [method]: cb,
[`${method}mw`]: middlewareArray, [`${method}mw`]: middleware as RouteCallback[],
}); });
console.log("route set:", method.toUpperCase(), path); console.log("route set:", method.toUpperCase(), path);