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)
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.
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.
In Koa, I know that "ctx" stands for context, which encapsulates node's request and response objects.
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.
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());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With