@hattip/compose
Middleware system for HatTip.
compose
The compose
function composes multiple handlers into a single one, creating a simple but powerful middleware system. Each handler is called in sequence until one returns a response. A handler can pass control to the next handler either by not returning anything or calling context.next()
. The latter allows the handler to modify the response before returning. Handler arrays passed to compose
is flattened and falsy values are filtered.
import { compose } from "@hattip/compose";
const urlParser = (ctx) => {
ctx.url = new URL(ctx.request.url);
};
const poweredBy = async (ctx) => {
const response = await ctx.next();
response.headers.set("X-Powered-By", "HatTip");
return response;
};
const homeHandler = (ctx) => {
if (ctx.url.pathname === "/") {
return new Response("Home");
}
};
const fooHandler = (ctx) => {
if (ctx.url.pathname === "/foo") {
return new Response("Foo");
}
};
const barHandler = (ctx) => {
if (ctx.url.pathname === "/bar") {
return new Response("Bar");
}
};
export default compose(
urlParser,
poweredBy,
homeHandler,
fooHandler,
barHandler,
);
compose
ends the handler chain with a final handler that calls context.passThrough
and returns a 404 response.
Handler
Handlers passed to compose
can return or throw a Request
object or any other object with a toResponse
method (which in turn returns a Response
) synchronously or asynchronously. Returning a falsy value implicitly passes the control to the next handler. Calling context.next()
does the same but explicitly and allows the handler to modify the response before returning.
RequestContext
Handlers are passed a single argument, an object representing the request context:
interface RequestContext {
request: Request;
ip: string;
platform: unknown;
passThrough(): void;
waitUntil(promise: Promise<any>): void;
url: URL;
method: string;
locals: Locals;
next(): Promise<Response>;
handleError(error: unknown): Response | Promise<Response>;
}