Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Variadic Route Handler Assignment #18

Closed
lukeed opened this issue Jan 26, 2018 · 3 comments
Closed

Variadic Route Handler Assignment #18

lukeed opened this issue Jan 26, 2018 · 3 comments

Comments

@lukeed
Copy link
Owner

lukeed commented Jan 26, 2018

Currently, Polka only allows 1 handler per route pattern. Express, on the other hand, allows you to assign as many as you want, constructing per-route middleware groups.

// no auth
app.get('/items', noop);

// require auth for posting
app.post('/items', authenticate, noop);

// no auth again
app.get('/items/:id', noop);

This is still a maybe as it would require changes to Trouter. Speed is still the #1 priority, and you can already achieve similar behavior by manually calling middleware from within the single handler.

Current "workaround"

function authenticate(req, res, next) {
  let token = req.headers.authorization;
  if (!token) return res.end('Token required!');
  // If used as middleware, iterate
  // But if not in loop, return "success" boolean
  return next ? next() : true;
}

// later, in app...

app.post('/items', (req, res) => {
  let isUser = authenticate(req, res); // <~ no next()
  if (!isUser) return; // already sent `res.end` before
  // Continue with route handler
  let body = req.body;
  // ...
});
@Youngestdev
Copy link

I think your current work around is cool.. Probably using the current workaround will be okay so far it doesn't affect the speed of polka.

@plakak
Copy link

plakak commented Feb 14, 2018

I'm strongly in favor of per route middleware. I just faced a case when I need to use different body-parser options for each route. I had to workaround it like shown in the example in docs (pathname.startsWith etc). but that's really not a pretty solution in my opinion.

@lukeed
Copy link
Owner Author

lukeed commented Feb 14, 2018

@plakak I hear ya. Still deciding. Please remember that you can can attach a global middleware that specifies which parser to use based on Content-Type. This is how that body-parser package works in the first place~!

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

No branches or pull requests

3 participants