docs(httpkernel): enhance class and interface documentation

- Improve JSDoc comments for `HttpKernel` and `IHttpKernel` to clarify
  purpose, usage, and type parameters.
- Add detailed descriptions for methods, parameters, and generics.
- Refine explanations of middleware pipeline, error handling, and
  contextual typing.
- Enhance readability and consistency in public API documentation.

Signed-off-by: Max P. <Mail@MPassarello.de>
This commit is contained in:
2025-05-07 16:45:37 +02:00
parent b7410b44dd
commit 6c4420d32f
2 changed files with 62 additions and 59 deletions

View File

@@ -20,26 +20,37 @@ import { RouteBuilder } from './RouteBuilder.ts';
import { createEmptyContext, normalizeError } from './Utils/mod.ts'; import { createEmptyContext, normalizeError } from './Utils/mod.ts';
/** /**
* The central HTTP kernel responsible for managing route definitions, * The `HttpKernel` is the central routing engine that manages the full HTTP request lifecycle.
* executing middleware chains, and dispatching HTTP requests to their handlers.
* *
* This class supports a fluent API for route registration and allows the injection * It enables:
* of custom response decorators and route builder factories for maximum flexibility and testability. * - Dynamic and static route registration via a fluent API
* - Execution of typed middleware chains and final route handlers
* - Injection of response decorators and factory overrides
* - Fine-grained error handling via typed status-code-based handlers
*
* The kernel is designed with generics for flexible context typing, strong type safety,
* and a clear extension point for advanced routing, DI, or tracing logic.
*
* @typeParam TContext - The global context type used for all requests handled by this kernel.
*/ */
export class HttpKernel<TContext extends IContext = IContext> export class HttpKernel<TContext extends IContext = IContext>
implements IHttpKernel<TContext> { implements IHttpKernel<TContext> {
private cfg: IHttpKernelConfig<TContext>; private cfg: IHttpKernelConfig<TContext>;
/** /**
* The list of internally registered routes, each with method, matcher, middleware, and handler. * The list of registered route definitions, including method, matcher,
* middleware pipeline, and final handler.
*/ */
private routes: IInternalRoute<TContext>[] = []; private routes: IInternalRoute<TContext>[] = [];
/** /**
* Creates a new instance of the `HttpKernel`. * Initializes the `HttpKernel` with optional configuration overrides.
* *
* @param decorateResponse - An optional response decorator function that is applied to all responses * Default components such as the route builder factory, response decorator,
* after the middleware/handler pipeline. Defaults to identity (no modification). * and 404/500 error handlers can be replaced by injecting a partial config.
* @param routeBuilderFactory - Optional factory for creating route builders. Defaults to using `RouteBuilder`. * Any omitted values fall back to sensible defaults.
*
* @param config - Partial kernel configuration. Missing fields are filled with defaults.
*/ */
public constructor( public constructor(
config?: DeepPartial<IHttpKernelConfig<TContext>>, config?: DeepPartial<IHttpKernelConfig<TContext>>,
@@ -82,9 +93,8 @@ export class HttpKernel<TContext extends IContext = IContext>
/** /**
* @inheritdoc * @inheritdoc
*/ public async handle( */
request: Request, public async handle(request: Request): Promise<Response> {
): Promise<Response> {
const url = new URL(request.url); const url = new URL(request.url);
const method = request.method.toUpperCase(); const method = request.method.toUpperCase();
@@ -112,11 +122,12 @@ export class HttpKernel<TContext extends IContext = IContext>
} }
/** /**
* Registers a finalized route by pushing it into the internal route list. * Finalizes and registers a route within the kernel.
* *
* This method is typically called by the route builder after `.handle()` is invoked. * This method is invoked internally by the route builder once
* `.handle()` is called. It appends the route to the internal list.
* *
* @param route - The fully constructed route including matcher, middlewares, and handler. * @param route - A fully constructed internal route object.
*/ */
private registerRoute<_TContext extends IContext = TContext>( private registerRoute<_TContext extends IContext = TContext>(
route: IInternalRoute<_TContext>, route: IInternalRoute<_TContext>,
@@ -125,24 +136,18 @@ export class HttpKernel<TContext extends IContext = IContext>
} }
/** /**
* Executes the complete request pipeline: middleware chain, final handler, and optional response decoration. * Executes the middleware and handler pipeline for a matched route.
* *
* Middleware functions are invoked sequentially in the order of registration. Each middleware * This function:
* receives a `next()` callback to advance to the next stage. If a middleware returns a `Response` * - Enforces linear middleware execution with `next()` tracking
* directly, the pipeline short-circuits. * - Validates middleware and handler types at runtime
* - Applies the optional response decorator post-processing
* - Handles all runtime errors via the configured 500 handler
* *
* After the final handler produces a response, it is passed through the configured response decorator, * @param ctx - The active request context passed to middleware and handler.
* which may modify it (e.g., adding headers or logging metadata). * @param middleware - Ordered middleware functions for this route.
* * @param handler - The final handler responsible for generating a response.
* Internal error handling ensures: * @returns The final HTTP `Response`, possibly decorated.
* - That `next()` is not called multiple times.
* - That all middleware and handlers are properly typed.
* - That thrown exceptions are routed to the 500-error handler.
*
* @param ctx - The current request context, including request data and shared state.
* @param middleware - An ordered list of middleware functions to invoke.
* @param handler - The terminal request handler to produce the response.
* @returns The final decorated `Response` object.
*/ */
private async executePipeline( private async executePipeline(
ctx: TContext, ctx: TContext,
@@ -158,7 +163,6 @@ export class HttpKernel<TContext extends IContext = IContext>
let lastIndex = -1; let lastIndex = -1;
const dispatch = async (currentIndex: number): Promise<Response> => { const dispatch = async (currentIndex: number): Promise<Response> => {
// Prevent middleware from invoking next() multiple times
if (currentIndex <= lastIndex) { if (currentIndex <= lastIndex) {
throw new Error('Middleware called `next()` multiple times'); throw new Error('Middleware called `next()` multiple times');
} }

View File

@@ -3,48 +3,47 @@ import { IRouteBuilder } from './IRouteBuilder.ts';
import { IRouteDefinition } from './IRouteDefinition.ts'; import { IRouteDefinition } from './IRouteDefinition.ts';
/** /**
* Defines the core interface for an HTTP kernel instance, responsible for * The `IHttpKernel` interface defines the public API for a type-safe, middleware-driven HTTP dispatching system.
* registering routes, orchestrating middleware pipelines, and dispatching
* incoming HTTP requests to the appropriate handler.
* *
* The kernel operates on a generic `IContext` type, which encapsulates the * Implementations of this interface are responsible for:
* request, typed state, route parameters, and query parameters for each request. * - Registering routes with optional per-route context typing
* - Handling incoming requests by matching and dispatching to appropriate handlers
* - Managing the complete middleware pipeline and final response generation
* *
* @template TContext The default context type for all registered routes and handlers. * The kernel operates on a customizable `IContext` type to support strongly typed request parameters, state,
* and query values across the entire routing lifecycle.
*
* @typeParam TContext - The default context type used for all routes unless overridden per-route.
*/ */
export interface IHttpKernel<TContext extends IContext = IContext> { export interface IHttpKernel<TContext extends IContext = IContext> {
/** /**
* Registers a new route using a static path or custom matcher. * Registers a new HTTP route (static or dynamic) and returns a route builder for middleware/handler chaining.
* *
* Returns a route builder that allows chaining middleware and assigning a final handler. * This method supports contextual polymorphism via the `_TContext` type parameter, enabling fine-grained
* This method is context-generic, allowing temporary overrides for specific routes * typing of route-specific `params`, `query`, and `state` values. The route is not registered until
* if their context differs from the kernel-wide default. * `.handle()` is called on the returned builder.
* *
* @template _TContext Optional context override for the specific route being registered. * @typeParam _TContext - An optional override for the context type specific to this route.
* Defaults to the kernel's generic `TContext`. * Falls back to the global `TContext` of the kernel if omitted.
* *
* @param definition - A route definition containing the HTTP method and either a path * @param definition - A route definition specifying the HTTP method and path or custom matcher.
* pattern (e.g., `/users/:id`) or a custom matcher function. * @returns A fluent builder interface to define middleware and attach a final handler.
* @returns A fluent builder interface for attaching middleware and setting the handler.
*/ */
route<_TContext extends IContext = TContext>( route<_TContext extends IContext = TContext>(
definition: IRouteDefinition, definition: IRouteDefinition,
): IRouteBuilder; // IRouteBuilder<_TContext> ): IRouteBuilder<_TContext>;
/** /**
* Handles an incoming HTTP request by matching it to a route, executing its middleware, * Handles an incoming HTTP request and produces a `Response`.
* and invoking the final handler. Automatically populates route parameters (`ctx.params`),
* query parameters (`ctx.query`), and initializes an empty mutable state (`ctx.state`).
* *
* This method is typically passed directly to `Deno.serve()` as the request handler. * The kernel matches the request against all registered routes by method and matcher,
* constructs a typed context, and executes the middleware/handler pipeline.
* If no route matches, a 404 error handler is invoked.
* *
* @template _TContext Optional override for the context type of the current request. * This method is designed to be passed directly to `Deno.serve()` or similar server frameworks.
* Useful for testing or simulated requests. Defaults to the kernel’s `TContext`.
* *
* @param request - The incoming HTTP request to dispatch. * @param request - The incoming HTTP request object.
* @returns A promise resolving to the final HTTP response. * @returns A `Promise` resolving to a complete HTTP response.
*/ */
handle( handle(request: Request): Promise<Response>;
request: Request,
): Promise<Response>;
} }