Cascading in Koa

Koa takes advantage of async functions to make middleware functions run in a truly cascaded fashion. The registered middlewares run in a stack-like manner and run from one level to the other until there is no other middleware to run.

The use of async functions is an improvement over other frameworks that have tried to implement stack-like middleware, as callbacks in Node made it much harder. Koa contrasts Connect, for example, in that Connect simply passes control through a series of functions until one returns. In Koa, the middleware functions are invoked downstream, and the control flows back upstream.

Here is an example from the Koa documentation showing the use of middleware:

const Koa = require('koa');
const app = new Koa();

// logger
app.use(async (ctx, next) => {
await next();
const rt = ctx.response.get('X-Response-Time');
console.log(`${ctx.method} ${ctx.url} - ${rt}`);
});

// x-response-time
app.use(async (ctx, next) => {
const start = Date.now();
await next();
const ms = Date.now() - start;
ctx.set('X-Response-Time', `${ms}ms`);
});

// response
app.use(async ctx => {
ctx.body = 'Hello World';
});

app.listen(3000);

In the preceding code block, the request first flows through the logger middleware, and then the x-response-time middleware, which marks when the request started, and finally the response middleware, which sends the Hello World response. When a middleware calls next(), the middleware function suspends and passes control to the next middleware defined. Once no other middleware exists to execute downstream, the stack will unwind and each middleware is resumed to perform its upstream behavior.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.133.141.6