lukeed / polka

A micro web server so fast, it'll make you dance! :dancers:
MIT License
5.43k stars 174 forks source link

Variadic Route Handler Assignment #18

Closed lukeed closed 6 years ago

lukeed commented 6 years ago

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 commented 6 years ago

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 commented 6 years ago

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 commented 6 years ago

@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~!