Skip to content

Instantly share code, notes, and snippets.

@kran
Last active September 6, 2016 10:11
Show Gist options
  • Save kran/4624213 to your computer and use it in GitHub Desktop.
Save kran/4624213 to your computer and use it in GitHub Desktop.
express.js controller demo , just for fun !
var Controller = function(route){
this.baseRoute = route;
};
Controller.prototype = {
actions: {},
filters: [],
baseRoute: '',
_beforeAction:function(){
var self = this;
return function(req, res, next){
try{
var pass = true;
var action = self._actionName(req);
if(!self.actions[action]) {
throw new Error('404: action not found');
}
for(var i=0;i<self.filters.length;i++){
var f = self.filters[i];
if(f.actions.indexOf(action) != -1){
if(f.check) pass = f.check.call(self, req, res);
if(!pass) {
throw new Error(f.message || "500: not allowed");
}
}
}
next();
}catch(e){
next(e)
}
};
},
run: function(app,path){
var self = this;
if(path) this.baseRoute = path;
app.all(this.baseRoute +"/(:action)?/?", self._beforeAction(), function(req, res, next){
var exists_action = self._getAction(req);
exists_action(req, res);
});
},
_getAction: function(req){
var action = this._actionName(req);
return this.actions[action];
},
_actionName: function(req){
var action = req.params.action;
var method = req.method.toLowerCase();
if(!action){ action = 'index'; }
if(this.actions[action+'_'+method]){
return action+'_'+method;
}
return action;
}
};
// *用法* //
//实例一个controller,默认路由到actions.index
var handle = new Controller('/page');
//向实例里添加动作
handle.actions.index = function(req, res){
res.send('index !!!')
};
//后缀是 _ + req.method.toLowerCase(), 覆盖普通的index
handle.actions.index_post= function(req, res){
res.send('post to index !!!')
};
//简陋的过滤器
handle.filters.push({
actions: ['index'],//要过滤的action列表
//check为过滤函数,心脏病法,遇到false就不再继续
//通过返回true,不通过返回false,也可以做redirect等其它动作
check: function(req, res){
return !!req.query.logged
},
//false时提供的错误信息
message:'Not logged in!'
});
exports = module.exports = handle
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment