Framework-agnostic middleware composition engine
npm install @philiprehberger/middleware-tsFramework-agnostic middleware composition engine
npm install @philiprehberger/middleware-ts
import { compose, createPipeline } from '@philiprehberger/middleware-ts';
type Ctx = { req: Request; user?: User };
const app = createPipeline<Ctx>()
.use(logger)
.useIf(requiresAuth, auth)
.use(handler)
.build();
await app({ req: new Request('/api') });
import { branch } from '@philiprehberger/middleware-ts';
const authBranch = branch(
(ctx) => ctx.req.url.startsWith('/api'),
authMiddleware,
publicMiddleware,
);
import { withTimeout, MiddlewareTimeoutError } from '@philiprehberger/middleware-ts';
const slowOp = withTimeout(async (ctx, next) => {
await fetchSomethingSlow(ctx);
await next();
}, 5000);
import { tap } from '@philiprehberger/middleware-ts';
const logger = tap<Ctx>((ctx) => {
console.log(`[req] ${ctx.req.url}`);
});
| Function | Description |
|---|---|
compose(...middlewares) | Compose into single middleware |
createPipeline<Ctx>() | Builder with .use() and .useIf() |
branch(condition, trueMw, falseMw?) | Conditional middleware |
withErrorHandler(mw, handler) | Wrap with error catching |
withTimeout(mw, ms) | Reject with MiddlewareTimeoutError if mw exceeds ms |
tap(fn) | Run a side-effect and continue the pipeline |
npm install
npm run build
npm test
If you find this project useful: