添加controller级别或者action级别中间件。
提供控制器级别 __before和__after这两个前后置action。
$ npm i egg-hook --save
启用插件
// {app_root}/config/plugin.js
exports.hook = {
enable: true,
package: 'egg-hook',
};
启动自定义文件中添加hook
//app.js
app.controllerHook('home', function *(next) {
console.log(this.controllerKey);//GET / => controller.index => controllerKey=>"home"
console.log(this.actionKey);// GET / => controller.index => actionKey="index"
this.body = "hi, ";
yield next;
});
//app.js
app.actionHook('home', 'index', function *(next) {
console.log(this.controllerKey);//GET / => controller.index => controllerKey=>"home"
console.log(this.actionKey);// GET / => controller.index => actionKey="index"
this.body += "hook";
yield next;
});
控制器前后置钩子
//app/controller/home.js
module.exports = app => {
return class home extends app.Controller {
__before(){
console.log("before");
const {ctx}=this;
if(!ctx.isLogin){
return ctx.preventNext();//skip index() and __after()
}
}
*index() {
console.log("action");
//ctx.preventNext() //skip __after()
}
__after(){
console.log("after");
}
}
}
Please open an issue here.