sunder icon indicating copy to clipboard operation
sunder copied to clipboard

Middleware on a Per-Route Basis

Open AddisonTustin opened this issue 3 years ago • 3 comments

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!

AddisonTustin avatar Jan 23 '22 08:01 AddisonTustin

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;
        }
    };
}

AddisonTustin avatar Jan 24 '22 01:01 AddisonTustin

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!

ptim avatar Feb 04 '22 13:02 ptim

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).

gzuidhof avatar Feb 08 '22 11:02 gzuidhof