间接中间件
和子中间件
app.use()
加载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');})