Middleware Compose With Types
Compose middleware functions with proper typing for request pipeline processing in web frameworks.
Code
type Context=Record<string,unknown>;type Next=()=>Promise<void>;type Middleware=(ctx:Context,next:Next)=>Promise<void>;export function compose(...middlewares:Middleware[]):Middleware{return async function(ctx,next){let index=-1;async function dispatch(i:number):Promise<void>{if(i<=index)throw new Error('next() called multiple times');index=i;const fn=middlewares[i];if(!fn)return next();await fn(ctx,()=>dispatch(i+1));}await dispatch(0);};}Report a problem with this exampleOpens a pre-filled issue on GitHub.