@philiprehberger/middleware-ts
v0.2.0
Published
Framework-agnostic middleware composition engine
Downloads
94
Readme
@philiprehberger/middleware-ts
Framework-agnostic middleware composition engine
Installation
npm install @philiprehberger/middleware-tsUsage
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') });Conditional Branching
import { branch } from '@philiprehberger/middleware-ts';
const authBranch = branch(
(ctx) => ctx.req.url.startsWith('/api'),
authMiddleware,
publicMiddleware,
);Timeout
import { withTimeout, MiddlewareTimeoutError } from '@philiprehberger/middleware-ts';
const slowOp = withTimeout(async (ctx, next) => {
await fetchSomethingSlow(ctx);
await next();
}, 5000);Tap (Side Effects)
import { tap } from '@philiprehberger/middleware-ts';
const logger = tap<Ctx>((ctx) => {
console.log(`[req] ${ctx.req.url}`);
});API
| 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 |
Development
npm install
npm run build
npm testSupport
If you find this project useful:
