Middleware on a Per-Route Basis
After looking at the project's documentation, and poking around with sunder for a bit, I was wondering if functionality exists to allow multiple middleware per route, say similar to koa-router.
If not, is that within the scope of any potential future work?
In any case, super awesome tool I'd love to use in the future!
After messing around a bit more, was able to come up with a potentially simple-enough solution that allows for a variable number of middlewares on a given route declaration. With some cursory testing it appears to work without issue.
Usage:
router.get('/my/api/path', withMiddlewares(middlewareOne, middlewareTwo, myHandler))
Declaration:
import { apply, Context, Handler } from 'sunder';
import { Env } from 'my/package/env';
import { PathParams } from 'sunder/middleware/router';
export const withMiddlewares = <T extends PathParams<any>, U>(...middlewares: Handler<Env, T, U>[]) => {
return async (ctx: Context<Env, T>) => {
try {
await apply(middlewares, ctx);
} catch (e) {
console.error(e);
throw e;
}
};
}
Ah! I think I just found provided solution using compose:
import { Router, compose } from 'sunder'
import { Env } from './bindings'
import { handleBar } from './handlers'
import { withFoo } from './middleware'
export function registerRoutes(router: Router<Env, any>) {
router.get('/', compose([withFoo, handleBar]))
}
Hth!
I think compose is the best answer here :). We could in the future allow multiple arguments instead (and if there are multiple, we call compose internally).