1

我正在为模块导出一个函数,以便我可以将变量传递到模块中。但是,我们的代码分析器报告该函数太长。

通常我这样做是为了将我的快速应用程序和一些配置传递到一个文件中,该文件将定义一些路由。我通常对每种资源都有不同的路由文件,以便进行一些分离:

routes/authors.js
routes/books.js
...
etc

在 authors.js 内部:

module.exports = function(app, configuration) {

  app.post('/authors', ...


  app.get('/authors', ...


  app.get('/authors/:id', ...

}

这很好用,但我最终得到了一个很长的函数。没什么大不了的,因为该功能由每条路线的许多相同功能组成。但是静态代码分析抱怨函数长度。

当然,也许这应该被忽略。但我也想确保这不是让代码变得更好的好机会,因为也许(只是也许)代码分析器是正确的。

有没有更好的方法来导出模块中的函数并避免真正长的函数?通过“更好”,我正在寻找可能是我不遵循的标准或约定的东西,如果我已经遵循 nodejs/express 约定,我不想更改代码。

4

1 回答 1

1

我一直这样做的方法是将我的路由方法放在一个单独的控制器文件中。

示例作者.controller.js:

module.exports = {
    getAuthorsById: function(req, res, next) {
        res.render('authors');
    },
    getAuthors: function(req, res, next) {
    },
    // Now if for some reason I need to configuration object passed into
    // the controller method I can simply return a function.
    postAuthor: function(conf) {
        return function(req, res, next) {
            if(conf.x) {
                res.render(conf.y);
            }
        }
    }
}

例如 authors.routes.js:

var ctrl = require('./authors.controller.js');

module.exports = function(app, conf) {
    app.get('/authors/:id', ctrl.getAuthorsById);
    app.get('/authors', ctrl.getAuthors);
    // And then pass in the configuration object when needed.
    app.post('/authors', ctrl.postAuthor(conf));
}();

这样定义路由的函数本身并不庞大,尽管控制器文件仍然可以很大。

于 2016-01-23T15:25:39.870 回答