广义中间件

前言

  • 不直接提供中间件
  • 通过间接方式提供了中间件,最常见的是间接中间件子中间件
  • 间接被 app.use() 加载
  • 其他方式接入Koa切面

间接中间件

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

function indirectMiddleware(path, middleware) {
  return async function(ctx, next) {
    console.log(ctx.path === path, middleware);
    if (ctx.path === path) {
      await middleware(ctx, next);
    } else {
      await next();
    }
  };
}

const index = async function(ctx, next) {
  ctx.body = 'this is index page';
};

const hello = async function(ctx, next) {
  ctx.body = 'this is hello page';
};

const world = async function(ctx, next) {
  ctx.body = 'this is world page';
};

app.use(indirectMiddleware('/', index));
app.use(indirectMiddleware('/hello', hello));
app.use(indirectMiddleware('/world', world));

app.listen(3001, () => {
  console.log('the demo is start at port 3001');
});

子中间件

子中间件是广义中间件的一个最有代表场景,主要的特点有

  • 初始化中间件时,内置子中间件列表
  • 子中间件列表添加子中间件元素
  • 子中间件列表封装成间接中间件,让后被app.use()加载
const Koa = require('koa');
let app = new Koa();

class Middleware{
  constructor() {
    this.stack = [];
  }

  get(path, childMiddleware) {
    this.stack.push({ path, middleware: childMiddleware })
  }

  middlewares() {
    let stack = this.stack;
    return async function(ctx, next) {
      let path = ctx.path;
      for( let i=0; i<stack.length; i++ ) {
        const child = stack[i];
        if( child && child.path === path && child.middleware ) {
          await child.middleware(ctx, next);
        }
      }
      await next();
    }
  }
}

const middleware = new Middleware();
middleware.get('/page/001', async(ctx, next) => { ctx.body = 'page 001' })
middleware.get('/page/002', async(ctx, next) => { ctx.body = 'page 002' })
middleware.get('/page/003', async(ctx, next) => { ctx.body = 'page 003' })

app.use(middleware.middlewares());

app.listen(3001, function(){
  console.log('the demo is start at port 3001');
})

results matching ""

    No results matching ""