Express自身帶強大的路由功能,這讓我們可以詳細拆分項目的需求,設計出優美的restful風格對外API。爲了方便實現上述功能,我加入了頁面控制器及腳本自動加載設計:
比如針對會員模塊,我們在app.js中指定了模塊的路由文件
app.use('/member', require('./routes/member'));
首先:針對POST和GET方法,分別定義如下路由規則:
router.get('/register', function(request, response, next)
{
var action = express.autoload('action_member_register');
action.handleGet(request, response, next);
});
router.post('/register', function(request, response, next)
{
var action = express.autoload('action_member_register');
action.handlePost(request, response, next);
});
這裏的express.autoload就是我們臨時加入一個自動加載機制,用於自動映射/scripts/action/member/register.js這個頁面控制器,具體代碼也非常簡單:
express.autoload = function(path){return require('./scripts/'+path.replace(/_/g,'/'));};
其次:實現頁面控制器基類,並在其中集成頁面助手
var action = function(){};
module.exports = new action();
action.prototype.isempty = function(elem)
{
return (elem === null || elem === undefined || elem === '');
};
最後:基於基類實現具體頁面控制器即可
var action = express.inherit('flap_core_action');
module.exports = action;
action.handlePost = function(request, response, next){};
這裏的express.inherit就是我們實現的自動繼承,實現如下:
express.inherit = function(path){return Object.create(express.autoload(path));};
如果不想自己寫,也可以使用框架自帶的util.inherit來實現。
測試:
如果擔心寫出錯,運行時大量創建臨時對象,我們可以在新加入的自動加載腳本中加上測試代碼,使用autocannon測試下。