0.0.4 • Published 7 years ago

egg-hook v0.0.4

Weekly downloads
2
License
MIT
Repository
github
Last release
7 years ago

egg-hook

NPM version build status Test coverage David deps Known Vulnerabilities npm download

添加controller级别或者action级别中间件。

提供控制器级别 before和after这两个前后置action。

安装

$ npm i egg-hook --save

用法

启用插件

// {app_root}/config/plugin.js
exports.hook = {
  enable: true,
  package: 'egg-hook',
};

启动自定义文件中添加hook

app.controllerHook(controllerKey,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.actionHook(controllerKey,actionKey,hook)

  //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");
        }
    }
}

应用场景

Questions & Suggestions

Please open an issue here.

License

MIT