简体   繁体   English

如何在 Express.js 中共享控制器之间的公共逻辑?

[英]How to share the common logic between controller in Express.js?

I had used the express to build my website, and I have a special require.I had set the routers as follow:我用express建网站,我有一个特殊的要求。我把路由器设置如下:

/* home */
app.get('/', function (req, res, next) {
    homeRacingHandle(req,res);
});

/* racing list */
app.get('/racing',function (req, res, next) {
    homeRacingHandle(req,res);
});

There is just a few differents between the home page and the racing list page .主页赛车列表页面之间只有一些不同之处。 My method to process the common logic is like above.And the homeRacingHandle function according the variable isHome to decide which page to render.我处理常用逻辑的方法如上,homeRacingHandle函数根据变量isHome来决定渲染哪个页面。

    var location = req.path.split('?').toString();
    var isHome = location==='/' && true || false;

This method works for me.But I don't know wether is a good way to process.Are there any other best practice?这种方法对我有用。但我不知道是否是处理的好方法。还有其他最佳实践吗?

You could use currying to simplify this你可以使用柯里化来简化这个

curryHomeRacing = require('./handler');

/* home */
app.get('/', curryHomeRacing('home'));

/* racing list */
app.get('/racing', curryHomeRacing('racing'));

In another file handler.js在另一个文件 handler.js 中

//in handler.js

module.exports = function curryHomeRacing(route){
    return function(req, res) {
        homeRacingHandle(req, res, route);
    };
}

function homeRacingHandle(req, res, route) {
    if (route === 'home') {
        //do home stuff
    } else if (route === 'racing') {
        //do racing stuff
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM