lukeed / polka

A micro web server so fast, it'll make you dance! :dancers:

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Migrating from Express

hrnnjrg opened this issue · comments

Hi,

I've been playing a bit with Polka and I'm seriously considering migrating my api server from Express to Polka. It's relatively simple, very little logic, just triggering DB queries with request data. Same as for middleware, only the usual Express boilerplate (helmet, cors, cookie parser, etc)

I'm not entirely sure what the best way forward would be in my case. I thought of start using Trouter first, and when that works, switching to Polka, where I would have to change all the res.send to what Polka uses.

Am I missing any low/high hanging fruit? Is there anything additional to consider when using a websocket server?

Thanks!

Hey, thanks

There's more work to be done if you're targeting a Trouter port. Polka === Trouter, but it adds subapplication and middleware management for you. With Trouter alone, you'd have to manually call this.find, decode params appropriately, and loop over all matched handlers correctly. Doable, but if you're looking for an Express-alike, then Polka(@next) is the closer fit.

Both projects will require you to add your response helpers manually. There will eventually be a Polka "compat" preset that has everything already bound for you, but generally, most applications only need a tiny subset of the full Express set.

For res.send specifically (and any others you want to add later), you can do something like this from the main application. You can do in every subrouter/subapplication, but it's repetitive and doesn't actually add anything. The same req/res objects are passed around too all handlers for the duration of the request.

// NOTE: Assumes all are @next tags
// ---
import polka from 'polka';
import send from '@polka/send';
import redirect from '@polka/redirect';

// subrouter #1
import Items from './routes/items';

polka()
  .use((req, res, next) => {
    res.send = send.bind(0, res);
    res.redirect = redirect.bind(0, res);
    // .. add any others
    next();
  })
  .use('/items', Items)
  .get('/alive', (req, res) => {
    res.send(200, 'OK');
  })
  .listen(3000);

Note: My @polka/send package isn't a 1:1 with Express' res.send, but it's just to show that you can attach multiple things at once.

Doing this makes res.send and res.redirect available to the entire rest of the application.

Hope this helps~! There will be a full guide once I'm able to take Polka@1.0 over the finish line.