Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Whats the point of composing middleware in Koa?

Tags:

koa

I am diving into Koa2 and I see koa-compose. I get that I give it middlewares and it returns one, but why? What is the benefit of having multiple middleware wrapped as one instead of just adding them separately?

app.use(compose(m1, m2))

vs:

app.use(m1)
app.use(m2)
like image 386
cyberwombat Avatar asked Aug 28 '16 00:08

cyberwombat


People also ask

What is middleware KOA?

Koa Application The application object is Koa's interface with node's http server and handles the registration of middleware, dispatching to the middleware from http, default error handling, as well as configuration of the context, request and response objects.

How do you write KOA middleware?

The way I write middleware is pretty similar with @Sebastian: const Koa = require('koa'); const app = new Koa(); const render = async(ctx, next) { // wait for some async action to finish await new Promise((resolve) => { setTimeout(resolve, 5000) }); // then, send response ctx. type = 'text/html'; ctx.

What is CTX in KOA?

In Koa, I know that "ctx" stands for context, which encapsulates node's request and response objects.

What is Koa coding?

Koa is a new web framework designed by the team behind Express, which aims to be a smaller, more expressive, and more robust foundation for web applications and APIs. By leveraging async functions, Koa allows you to ditch callbacks and greatly increase error-handling.


1 Answers

KoaJS uses koa-compose underneath (here), so app.use(compoase([m1,m2])); and app.use(m1); app.use(m2); are the same. Using koa-compose explicitly can give more power for customization. Following is one such case:

Adding middlewares through app.use(middleware), will cause all of the middlewares to be executed upon each request in the specified order. But if you want to selectively run different set of middlewares for each route (or in a different order), you can use explicitly use koa-compose to create specialized middleware stacks for each route.

var app = require('koa')();
var router = require('koa-router')();
var compose = require('koa-compose');

var allMiddlewares = compose([m1,m2,m3]);

router.get('/', allMiddlewares);
// selectively enable logging middleware for this route
router.get('/test', compose(logger, allMiddlewares));

app
  .use(router.routes())
  .use(router.allowedMethods());
like image 183
zeronone Avatar answered Sep 28 '22 13:09

zeronone