减less输出模块时的function长度

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

通常我这样做是为了将我的快车应用程序和一些configuration传递给定义一些路线的文件。 我通常有不同的路线文件,每个资源只是给一些分离:

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

在authors.js里面:

 module.exports = function(app, configuration) { app.post('/authors', ... app.get('/authors', ... app.get('/authors/:id', ... } 

这工作很好,但我最终有一个很长的function。 没有什么大不了的,因为每个路由的function都是由许多相同的function组成的。 但静态代码分析抱怨function长度。

当然,也许这是应该被忽略的东西。 但是我也想确定这不是一个好的机会,使代码更好一点,也许(也许)代码分析器是正确的。

有没有更好的方式来导出模块中的function,并避免真正的长期function? 而“更好”的是,我正在寻找一些可能是我不遵守的标准或惯例,如果我已经遵循了nodejs / express约定,我不想更改代码。

我一直在做的方式是把我的路线方法放在一个单独的控制器文件中。

示例authors.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)); }(); 

这样路由定义的function本身并不大,尽pipe控制器文件还是可以的。

Interesting Posts