广义中间件
前言
- 不直接提供中间件
- 通过间接方式提供了中间件,最常见的是
间接中间件
和子中间件
- 间接被
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');
})
当前内容版权归 chenshenhai 或其关联方所有,如需对内容或内容相关联开源项目进行关注与资助,请访问 chenshenhai .