Files
http-kernel/src/RouteBuilder.ts
Max P. 8235680904 refactor(types): unify handler and middleware definitions
- Consolidates `Handler` and `Middleware` types under `Types` module
- Replaces `IHandler` and `IMiddleware` interfaces with typed functions
- Simplifies imports and improves code organization
- Enhances debugging with named handlers and middlewares
2025-05-08 19:03:18 +02:00

68 lines
2.4 KiB
TypeScript

import { IRouteMatcherFactory } from './Interfaces/IRouteMatcher.ts';
import { IContext, IRouteBuilder, IRouteDefinition } from './Interfaces/mod.ts';
import { Handler, Middleware, RegisterRoute } from './Types/mod.ts';
import { createRouteMatcher } from './Utils/createRouteMatcher.ts';
/**
* Provides a fluent builder interface for defining a single route,
* including HTTP method, path or matcher, middleware chain and final handler.
*
* This builder is stateless and immutable; each chained call returns a new instance.
*/
export class RouteBuilder<TContext extends IContext = IContext>
implements IRouteBuilder<TContext> {
/**
* Constructs a new instance of the route builder.
*
* @param registerRoute - A delegate used to register the finalized route definition.
* @param def - The route definition (static path or dynamic matcher).
* @param mws - The list of middleware functions collected so far (default: empty).
*/
constructor(
private readonly registerRoute: RegisterRoute<TContext>,
private readonly def: IRouteDefinition,
private readonly mws: Middleware<TContext>[] = [],
private readonly matcherFactory: IRouteMatcherFactory =
createRouteMatcher,
) {}
/**
* Adds a middleware function to the current route definition.
*
* Middleware is executed in the order it is added.
* Returns a new builder instance with the additional middleware appended.
*
* @param mw - A middleware function to be executed before the handler.
* @returns A new `RouteBuilder` instance for continued chaining.
*/
middleware(
mw: Middleware<TContext>,
): IRouteBuilder<TContext> {
return new RouteBuilder<TContext>(
this.registerRoute,
this.def,
[...this.mws, mw],
);
}
/**
* Finalizes the route by assigning the handler and registering the route.
*
* Internally constructs a matcher function from the route definition
* and passes all route data to the registration delegate.
*
* @param handler - The final request handler for this route.
*/
handle(
handler: Handler<TContext>,
): void {
const matcher = this.matcherFactory(this.def);
this.registerRoute({
method: this.def.method,
matcher,
middlewares: this.mws,
handler: handler,
});
}
}