Talking about Koa Onion Model

We already know that koa2middleware is based on the async/awaitrealization that the implementation process is driven by the next, so koa2there is a special execution order, we set up a model called for the implementation of this order - onion model.


Now imagine that you have a toothpick in your hand, passing through an onion horizontally, will it penetrate layer by layer? Go in from the first layer, to the second layer, the third... and then to the middle layer, and then penetrate layer by layer, from the third layer, the second layer, the first layer... In fact, the execution order of our koa2 middleware is also like this. Putting aside the business code, use an example from the koa2 official website to experiment

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

// logger
app.use(async (ctx, next) => {
    
    
  console.log('第一层洋葱 - 开始')
  await next();
  const rt = ctx.response.get('X-Response-Time');
  console.log(`${
      
      ctx.method} ${
      
      ctx.url} - ${
      
      rt}`);
  console.log('第一层洋葱 - 结束')
});

// x-response-time
app.use(async (ctx, next) => {
    
    
  console.log('第二层洋葱 - 开始')
  const start = Date.now();
  await next();
  const ms = Date.now() - start;
  ctx.set('X-Response-Time', `${
      
      ms}ms`);
  console.log('第二层洋葱 - 结束')
});

// response
app.use(async ctx => {
    
    
  console.log('第三层洋葱 - 开始')
  ctx.body = 'Hello World';
  console.log('第三层洋葱 - 结束')
});

app.listen(8000);

Let's execute the above code. You will find that the print result is

第一层洋葱 - 开始
第二层洋葱 - 开始
第三层洋葱 - 开始
第三层洋葱 - 结束
第二层洋葱 - 结束
第一层洋葱 - 结束

Guess you like

Origin blog.csdn.net/Ruffaim/article/details/115038504