Skip to content
This repository has been archived by the owner on May 3, 2024. It is now read-only.

Middleware on a Per-Route Basis #6

Open
AddisonTustin opened this issue Jan 23, 2022 · 3 comments
Open

Middleware on a Per-Route Basis #6

AddisonTustin opened this issue Jan 23, 2022 · 3 comments

Comments

@AddisonTustin
Copy link

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
Copy link
Author

AddisonTustin commented Jan 24, 2022

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

@ptim
Copy link

ptim commented Feb 4, 2022

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!

@gzuidhof
Copy link
Collaborator

gzuidhof commented Feb 8, 2022

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

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants